@luma.gl/graph 10.0.0-alpha.11 → 10.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/dist.dev.js +658 -292
  2. package/dist/dist.min.js +110 -92
  3. package/dist/experimental/index.cjs.map +1 -1
  4. package/dist/experimental/simulation/index.cjs.map +1 -1
  5. package/dist/gpu-core/compiled-gpu-graph.cjs +15 -0
  6. package/dist/gpu-core/compiled-gpu-graph.d.ts +1 -0
  7. package/dist/gpu-core/compiled-gpu-graph.d.ts.map +1 -1
  8. package/dist/gpu-core/compiled-gpu-graph.js +15 -0
  9. package/dist/gpu-core/compiled-gpu-graph.js.map +1 -1
  10. package/dist/gpu-core/gpu-command-graph.cjs +9 -0
  11. package/dist/gpu-core/gpu-command-graph.d.ts +2 -0
  12. package/dist/gpu-core/gpu-command-graph.d.ts.map +1 -1
  13. package/dist/gpu-core/gpu-command-graph.js +9 -0
  14. package/dist/gpu-core/gpu-command-graph.js.map +1 -1
  15. package/dist/gpu-core/gpu-expression-plan.cjs +4 -0
  16. package/dist/gpu-core/gpu-expression-plan.d.ts.map +1 -1
  17. package/dist/gpu-core/gpu-expression-plan.js +5 -0
  18. package/dist/gpu-core/gpu-expression-plan.js.map +1 -1
  19. package/dist/gpu-core/gpu-shader-pass-kernel.cjs +267 -0
  20. package/dist/gpu-core/gpu-shader-pass-kernel.d.ts +29 -0
  21. package/dist/gpu-core/gpu-shader-pass-kernel.d.ts.map +1 -0
  22. package/dist/gpu-core/gpu-shader-pass-kernel.js +260 -0
  23. package/dist/gpu-core/gpu-shader-pass-kernel.js.map +1 -0
  24. package/dist/gpu-core/gpu-shader-pass-operation.cjs +85 -0
  25. package/dist/gpu-core/gpu-shader-pass-operation.d.ts +32 -0
  26. package/dist/gpu-core/gpu-shader-pass-operation.d.ts.map +1 -0
  27. package/dist/gpu-core/gpu-shader-pass-operation.js +74 -0
  28. package/dist/gpu-core/gpu-shader-pass-operation.js.map +1 -0
  29. package/dist/gpu-core/index.cjs +3 -0
  30. package/dist/gpu-core/index.cjs.map +3 -3
  31. package/dist/gpu-core/index.d.ts +2 -0
  32. package/dist/gpu-core/index.d.ts.map +1 -1
  33. package/dist/gpu-core/index.js +1 -0
  34. package/dist/gpu-core/index.js.map +1 -1
  35. package/dist/gpu-dggs/benchmarks.cjs.map +1 -1
  36. package/dist/gpu-graph/index.cjs.map +3 -3
  37. package/dist/gpu-graph-algorithms/benchmarks.cjs.map +1 -1
  38. package/dist/gpu-physics/index.cjs.map +1 -1
  39. package/dist/gpu-project/graph.cjs.map +3 -3
  40. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.cjs +53 -5
  41. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.d.ts +3 -1
  42. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.d.ts.map +1 -1
  43. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.js +58 -5
  44. package/dist/gpu-simple-graph/compiled-gpu-expression-graph.js.map +1 -1
  45. package/dist/gpu-simple-graph/index.cjs.map +3 -3
  46. package/dist/index.cjs +3 -0
  47. package/dist/index.cjs.map +3 -3
  48. package/dist/index.d.ts +2 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -0
  51. package/dist/index.js.map +1 -1
  52. package/package.json +7 -7
  53. package/src/gpu-core/compiled-gpu-graph.ts +18 -0
  54. package/src/gpu-core/gpu-command-graph.ts +10 -0
  55. package/src/gpu-core/gpu-expression-plan.ts +6 -0
  56. package/src/gpu-core/gpu-shader-pass-kernel.ts +307 -0
  57. package/src/gpu-core/gpu-shader-pass-operation.ts +103 -0
  58. package/src/gpu-core/index.ts +2 -0
  59. package/src/gpu-simple-graph/compiled-gpu-expression-graph.ts +59 -5
  60. package/src/index.ts +2 -0
package/dist/dist.min.js CHANGED
@@ -4,9 +4,9 @@
4
4
  else if (typeof define === 'function' && define.amd) define([], factory);
5
5
  else if (typeof exports === 'object') exports['luma'] = factory();
6
6
  else root['luma'] = factory();})(globalThis, function () {
7
- "use strict";var __exports__=(()=>{var Ts=Object.create;var yr=Object.defineProperty;var vs=Object.getOwnPropertyDescriptor;var Ss=Object.getOwnPropertyNames;var Es=Object.getPrototypeOf,Ps=Object.prototype.hasOwnProperty;var Cs=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ls=(r,e)=>{for(var t in e)yr(r,t,{get:e[t],enumerable:!0})},gr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ss(e))!Ps.call(r,i)&&i!==t&&yr(r,i,{get:()=>e[i],enumerable:!(n=vs(e,i))||n.enumerable});return r},br=(r,e,t)=>(gr(r,e,"default"),t&&gr(t,e,"default")),V=(r,e,t)=>(t=r!=null?Ts(Es(r)):{},gr(e||!r||!r.__esModule?yr(t,"default",{value:r,enumerable:!0}):t,r)),Bs=r=>gr(yr({},"__esModule",{value:!0}),r);var R=Cs((ju,Io)=>{Io.exports=globalThis.luma});var pr={};Ls(pr,{CompiledGPUCommandGraph:()=>lt,CompiledGPUGraph:()=>Mt,DynamicBuffer:()=>xe,DynamicTexture:()=>Ze,GPUCPUOperation:()=>ye,GPUCommandGraph:()=>ht,GPUCommandGraphAutotuner:()=>nn,GPUCommandGraphEncoding:()=>Dt,GPUCommandGraphExecution:()=>Gt,GPUCommandGraphExecutionBudgetController:()=>on,GPUCommandGraphInspector:()=>an,GPUCompactionOperation:()=>dn,GPUCopyOperation:()=>Ve,GPUExpressionOperation:()=>Ie,GPUGraph:()=>Pe,GPUGraphCompiler:()=>xt,GPUGraphScalar:()=>Oe,GPUGraphTexture:()=>ie,GPUGraphTextureView:()=>Ue,GPUGraphVector:()=>K,GPUUploadOperation:()=>Me,GraphBufferHandle:()=>Fe,GraphDataView:()=>Ge,GraphExternalTextureHandle:()=>nt,GraphTextureHandle:()=>ve,GraphTextureView:()=>De,GraphVectorView:()=>D,Kernel:()=>_,PreparedGPUGraphExecution:()=>lr,RenderKernel:()=>cn,composite:()=>So,getGPUCommandGraphAdapterIdentity:()=>ps,getGPUCommandGraphExecutionPlan:()=>$r,getPlatformInfo:()=>xs,gpuGraph:()=>W,inspectGPUGraphCompilation:()=>Eo,validateGPUGraph:()=>ur});br(pr,V(R(),1));var at=V(R(),1);async function $o(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof at.Buffer){if(!(r.usage&at.Buffer.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");let c=e.byteOffset??0,f=Math.min(256,e.byteLength??r.byteLength-c);if(c<0||f<0||c+f>r.byteLength)throw new Error("Preview range is outside the buffer.");return{data:f?await r.readAsync(c,f):new Uint8Array,format:e.format}}let t=r.device.getTextureFormatInfo(r.format);if(t.packed)throw new Error("Packed texture previews are not supported.");if(r.device.type!=="webgpu")throw new Error("Texture previews require WebGPU.");if(!((r.props.usage??0)&at.Texture.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");if(r.samples!==1||t.compressed||r.format.startsWith("depth")||r.format.startsWith("stencil"))throw new Error("Preview requires a single-sample, uncompressed color texture.");let n=e.baseMipLevel??0,i=Math.min(32,e.width??Math.max(1,r.width>>n)),o=Math.min(32,e.height??Math.max(1,r.height>>n)),s=r.computeMemoryLayout({width:i,height:o,depthOrArrayLayers:1}),a=r.device.createBuffer({byteLength:s.byteLength,usage:at.Buffer.MAP_READ|at.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:a,mipLevel:n,origin:[0,0,e.baseArrayLayer??0],width:i,height:o,depthOrArrayLayers:1,bytesPerRow:s.bytesPerRow}),r.device.submit(u.finish());let c=await a.readAsync(),f=i*t.bytesPerPixel,d=new Uint8Array(f*o);for(let l=0;l<o;l++)d.set(c.subarray(l*s.bytesPerRow,l*s.bytesPerRow+f),l*f);return{data:d,width:i,height:o,format:r.format}}finally{a.destroy(),u.destroy()}}var oe=V(R(),1);var Vt=globalThis,Gs=globalThis.document||{},xr=globalThis.process||{},Ds=globalThis.console,Os=globalThis.navigator||{};function wr(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 qe(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||wr()}var fn="5.0.0";function Tt(r,e){if(!r)throw new Error(e||"Assertion failed")}function Tr(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 Tt(Number.isFinite(e)&&e>=0),e}function ln(r){let{logLevel:e,message:t}=r;r.logLevel=Tr(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 Tt(i==="string"||i==="object"),Object.assign(r,{args:n},r.opts)}var Ye=()=>{},ut=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,o={}){let s=ln({logLevel:t,message:n,args:this._buildArgs(t,n,i),opts:o});return this._createLogFunction(e,s,o)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return Ye;let i=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&i!==void 0){if(this._onceCache.has(i))return Ye;this._onceCache.add(i)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=Tr(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function Is(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var Nt=class{constructor(e,t,n="sessionStorage"){this.storage=Is(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 ko(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 hn(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var zt;(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"})(zt||(zt={}));var $s=10;function Ao(r){return typeof r!="string"?r:(r=r.toUpperCase(),zt[r]||zt.WHITE)}function mn(r,e,t){return!qe&&typeof r=="string"&&(e&&(r=`\x1B[${Ao(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${Ao(t)+$s}m${r}\x1B[49m`)),r}function pn(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),i=r;for(let o of n){let s=i[o];typeof s=="function"&&(e.find(a=>o===a)||(i[o]=s.bind(r)))}}var vr=class{getHighResolutionTimer(){let e;if(qe()&&Vt.performance)e=Vt?.performance?.now?.();else if("hrtime"in xr){let t=xr?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=Vt?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},fe=new vr;globalThis.Probe=vr;globalThis.probe=fe;var vt={debug:qe()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},gn={enabled:!0,level:0},$e=class extends ut{constructor({id:e}={id:""}){super({level:0}),this.VERSION=fn,this._startTs=fe.getHighResolutionTimer(),this._deltaTs=fe.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new Nt(`__probe-${this.id}__`,{[this.id]:gn}),this.timeStamp(`${this.id} started`),pn(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((fe.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((fe.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:vt.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:vt.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=fe.getMemoryUsageMB();if(i!==null){let o=`${i}MB `;typeof t=="function"?t=()=>`${o}${t()}`:typeof t=="string"&&(t=`${o}${t}`)}return this._log("log",e,t,n,{method:vt.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:vt.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:vt.debug||vt.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||Ye,tag:As(t)}):Ye}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||Ye})}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||Ye})}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;Tt(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=fe.getHighResolutionTimer();let i=ks(this.id,t.message,t);return n.bind(console,i,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(gn),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...gn};this._storage.setConfiguration({[this.id]:{...t,...e}})}};$e.VERSION=fn;function ks(r,e,t){if(typeof e=="string"){let n=t.time?hn(ko(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=mn(e,t.color,t.background)}return e}function As(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=fe);var Hc=new $e({id:"@probe.gl/log"});var be=new $e({id:"luma.gl"});var yn={};function St(r="id"){yn[r]=yn[r]||1;let e=yn[r]++;return`${r}-${e}`}var _s="cpu-hotspot-profiler",_o="GPU Resource Counts",Fo="Resource Counts",Ro="GPU Time and Memory",Fs=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Rs=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Ms=Fs.flatMap(r=>[`${r} Created`,`${r} Active`]),Vs=Rs.flatMap(r=>[`${r} Created`,`${r} Active`]),Mo=new WeakMap,Vo=new WeakMap,le=class{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;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;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(!e)throw new Error("no device");this._device=e,this.props=Ns(t,n);let i=this.props.id!=="undefined"?this.props.id:St(this[Symbol.toStringTag]);this.props.id=i,this.id=i,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=Wt(this._device),t=e?Xe():0,n=[this._device.statsManager.getStats(_o),this._device.statsManager.getStats(Fo)],i=zo(this._device);for(let s of n)No(s,i);let o=this.getStatsName();for(let s of n)s.get("Resources Active").decrementCount(),s.get(`${o}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(Xe()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=Wt(this._device),i=n?Xe():0,o=this._device.statsManager.getStats(Ro);this.allocatedBytes>0&&this.allocatedBytesName&&(o.get("GPU Memory").subtractCount(this.allocatedBytes),o.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),o.get("GPU Memory").addCount(e),o.get(`${t} Memory`).addCount(e),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(Xe()-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=Wt(this._device),n=t?Xe():0,i=this._device.statsManager.getStats(Ro);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)+(Xe()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=Wt(this._device),n=t?Xe():0,i=[this._device.statsManager.getStats(_o),this._device.statsManager.getStats(Fo)],o=zo(this._device);for(let s of i)No(s,o);for(let s of i)s.get("Resources Created").incrementCount(),s.get("Resources Active").incrementCount(),s.get(`${e}s Created`).incrementCount(),s.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(Xe()-n)),zs(this._device,e)}getStatsName(){return Ws(this)}};function Ns(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function No(r,e){let t=r.stats,n=!1;for(let u of e)t[u]||(r.get(u),n=!0);let i=Object.keys(t).length,o=Mo.get(r);if(!n&&o?.orderedStatNames===e&&o.statCount===i)return;let s={},a=Vo.get(e);a||(a=new Set(e),Vo.set(e,a));for(let u of e)t[u]&&(s[u]=t[u]);for(let[u,c]of Object.entries(t))a.has(u)||(s[u]=c);for(let u of Object.keys(t))delete t[u];Object.assign(t,s),Mo.set(r,{orderedStatNames:e,statCount:i})}function zo(r){return r.type==="webgl"?Vs:Ms}function Wt(r){let e=r.userData[_s];return e?.enabled?e:null}function Xe(){return globalThis.performance?.now?.()??Date.now()}function zs(r,e){let t=Wt(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 Ws(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===le.prototype)return js(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function js(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 Ce=class r extends le{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,o;ArrayBuffer.isView(e)?(i=e,o=e.buffer):o=e;let s=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(o===null)this.debugData=new ArrayBuffer(s);else{let a=Math.min(i?.byteOffset||0,o.byteLength),u=Math.max(0,o.byteLength-a),c=Math.min(s,u);this.debugData=new Uint8Array(o,a,c).slice().buffer}}static defaultProps={...le.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var bn=globalThis.Float16Array;function Wo(){return bn??Uint16Array}function jo(r){return!!(bn&&r===bn)}function Sr(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}function Ho(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),i=xn[r],[o,s,a]=i||["uint8 ","i32",1];return{signedType:o,primitiveType:s,byteLength:a,normalized:e,integer:t,signed:n}}function qo(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 Hs(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(jo(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(xn).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function Yo(r){return Hs(r)}function qs(r){if(r==="float16")return Wo();let e=xn[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function Xo(r){return qs(r)}var xn={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 wn=class{getDataTypeInfo(e){return Ho(e)}getNormalizedDataType(e){return qo(e)}alignTo(e,t){return Sr(e,t)}getDataType(e){return Yo(e)}getTypedArrayConstructor(e){return Xo(e)}},Ko=new wn;var te="texture-compression-bc",A="texture-compression-astc",Le="texture-compression-etc2",Qo="texture-compression-etc1-webgl",Er="texture-compression-pvrtc-webgl",Tn="texture-compression-atc-webgl",Pr="float32-renderable-webgl",vn="float16-renderable-webgl",Ys="rgb9e5ufloat-renderable-webgl",Sn="snorm8-renderable-webgl",Ke="norm16-webgl",En="norm16-renderable-webgl",Pn="snorm16-renderable-webgl",Cr="float32-filterable",Zo="float16-filterable-webgl",jt=1,Ht=2,Bn=4,Gn=8,Pt=16,Br=5,ei=10,X=jt|Ht,Lr=jt|Bn,ke=jt|Ht|Bn|Gn,Be=jt|Ht|Pt,Xs=jt|Bn|Pt,Ln=ke|Pt,Jo=(Ht|Gn|Pt)<<Br,Ks=(Ht|Gn)<<Br,ne=Pt<<Br,Et=Ln<<Br,Qs=ke<<ei,Cn=Pt<<ei;function Gr(r){let e=ea[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var Zs={r8unorm:{webgpu:ke|ne},rg8unorm:{webgpu:ke|ne},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:Ln},"rgba8unorm-srgb":{webgpu:ke},r8snorm:{render:Sn,webgpu:Lr|Jo},rg8snorm:{render:Sn,webgpu:Lr|Jo},"rgb8snorm-webgl":{},rgba8snorm:{render:Sn,webgpu:Xs|Ks},r8uint:{webgpu:X|ne},rg8uint:{webgpu:X|ne},rgba8uint:{webgpu:Be},r8sint:{webgpu:X|ne},rg8sint:{webgpu:X|ne},rgba8sint:{webgpu:Be},bgra8unorm:{webgpu:ke},"bgra8unorm-srgb":{webgpu:Qs},r16unorm:{f:Ke,render:En,webgpu:Et},rg16unorm:{f:Ke,render:En,webgpu:Et},"rgb16unorm-webgl":{f:Ke,render:!1},rgba16unorm:{f:Ke,render:En,webgpu:Et},r16snorm:{f:Ke,render:Pn,webgpu:Et},rg16snorm:{f:Ke,render:Pn,webgpu:Et},"rgb16snorm-webgl":{f:Ke,render:!1},rgba16snorm:{f:Ke,render:Pn,webgpu:Et},r16uint:{webgpu:X|ne},rg16uint:{webgpu:X|ne},rgba16uint:{webgpu:Be},r16sint:{webgpu:X|ne},rg16sint:{webgpu:X|ne},rgba16sint:{webgpu:Be},r16float:{render:vn,filter:"float16-filterable-webgl",webgpu:ke|ne},rg16float:{render:vn,filter:Zo,webgpu:ke|ne},rgba16float:{render:vn,filter:Zo,webgpu:Ln},r32uint:{webgpu:Be},rg32uint:{webgpu:X|Cn},rgba32uint:{webgpu:Be},r32sint:{webgpu:Be},rg32sint:{webgpu:X|Cn},rgba32sint:{webgpu:Be},r32float:{render:Pr,filter:Cr,webgpu:Be},rg32float:{render:!1,filter:Cr,webgpu:X|Cn},"rgb32float-webgl":{render:Pr,filter:Cr},rgba32float:{render:Pr,filter:Cr,webgpu:Be},"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:Ys,webgpu:Lr},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Pr,webgpu:Lr|ne},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:ke|ne},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:X|ne},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:X},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:X},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:X},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:X},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:X},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:X}},Js={"bc1-rgb-unorm-webgl":{f:te},"bc1-rgb-unorm-srgb-webgl":{f:te},"bc1-rgba-unorm":{f:te},"bc1-rgba-unorm-srgb":{f:te},"bc2-rgba-unorm":{f:te},"bc2-rgba-unorm-srgb":{f:te},"bc3-rgba-unorm":{f:te},"bc3-rgba-unorm-srgb":{f:te},"bc4-r-unorm":{f:te},"bc4-r-snorm":{f:te},"bc5-rg-unorm":{f:te},"bc5-rg-snorm":{f:te},"bc6h-rgb-ufloat":{f:te},"bc6h-rgb-float":{f:te},"bc7-rgba-unorm":{f:te},"bc7-rgba-unorm-srgb":{f:te},"etc2-rgb8unorm":{f:Le},"etc2-rgb8unorm-srgb":{f:Le},"etc2-rgb8a1unorm":{f:Le},"etc2-rgb8a1unorm-srgb":{f:Le},"etc2-rgba8unorm":{f:Le},"etc2-rgba8unorm-srgb":{f:Le},"eac-r11unorm":{f:Le},"eac-r11snorm":{f:Le},"eac-rg11unorm":{f:Le},"eac-rg11snorm":{f:Le},"astc-4x4-unorm":{f:A},"astc-4x4-unorm-srgb":{f:A},"astc-5x4-unorm":{f:A},"astc-5x4-unorm-srgb":{f:A},"astc-5x5-unorm":{f:A},"astc-5x5-unorm-srgb":{f:A},"astc-6x5-unorm":{f:A},"astc-6x5-unorm-srgb":{f:A},"astc-6x6-unorm":{f:A},"astc-6x6-unorm-srgb":{f:A},"astc-8x5-unorm":{f:A},"astc-8x5-unorm-srgb":{f:A},"astc-8x6-unorm":{f:A},"astc-8x6-unorm-srgb":{f:A},"astc-8x8-unorm":{f:A},"astc-8x8-unorm-srgb":{f:A},"astc-10x5-unorm":{f:A},"astc-10x5-unorm-srgb":{f:A},"astc-10x6-unorm":{f:A},"astc-10x6-unorm-srgb":{f:A},"astc-10x8-unorm":{f:A},"astc-10x8-unorm-srgb":{f:A},"astc-10x10-unorm":{f:A},"astc-10x10-unorm-srgb":{f:A},"astc-12x10-unorm":{f:A},"astc-12x10-unorm-srgb":{f:A},"astc-12x12-unorm":{f:A},"astc-12x12-unorm-srgb":{f:A},"pvrtc-rgb4unorm-webgl":{f:Er},"pvrtc-rgba4unorm-webgl":{f:Er},"pvrtc-rgb2unorm-webgl":{f:Er},"pvrtc-rgba2unorm-webgl":{f:Er},"etc1-rgb-unorm-webgl":{f:Qo},"etc1-rbg-unorm-webgl":{f:Qo},"atc-rgb-unorm-webgl":{f:Tn},"atc-rgba-unorm-webgl":{f:Tn},"atc-rgbai-unorm-webgl":{f:Tn}},ea={...Zs,...Js};var ta=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,ra=["rgb","rgba","bgra"],na=["depth","stencil"],oa=5,ia=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Dn=class{isColor(e){return ra.some(t=>e.startsWith(t))}isDepthStencil(e){return na.some(t=>e.startsWith(t))}isCompressed(e){return ia.some(t=>e.startsWith(t))}getInfo(e){return ti(e)}getCapabilities(e){return aa(e)}getWebGPUCapabilities(e){let t=Gr(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?oa:0}computeMemoryLayout(e){return sa(e)}},ct=new Dn;function sa({format:r,width:e,height:t,depth:n,byteAlignment:i}){let o=ct.getInfo(r),{bytesPerPixel:s,bytesPerBlock:a=s,blockWidth:u=1,blockHeight:c=1,compressed:f=!1}=o,d=f?Math.ceil(e/u):e,l=f?Math.ceil(t/c):t,h=d*a,m=Math.ceil(h/i)*i,p=l,y=m*p*n;return{bytesPerPixel:s,bytesPerRow:m,rowsPerImage:p,depthOrArrayLayers:n,bytesPerImage:m*p,byteLength:y}}function aa(r){let e=Gr(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=ti(r),i=r.startsWith("depth")||r.startsWith("stencil"),o=n?.signed,s=n?.integer,a=n?.webgl,u=!!n?.compressed;return t.render&&=!i&&!u,t.filter&&=!i&&!o&&!s&&!a,t}function ti(r){let e=ua(r);if(ct.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=da(r);let n=ca(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:ta.exec(r);if(t){let[,n,i,o,s,a]=t,u=`${o}${i}`,c=Ko.getDataTypeInfo(u),f=c.byteLength*8,d=n?.length??1,l=[f,d>=2?f:0,d>=3?f:0,d>=4?f:0];e={format:r,attachment:e.attachment,dataType:c.signedType,components:d,channels:n,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:l,bytesPerPixel:c.byteLength*d,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),s==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function ua(r){let e={...Gr(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 ca(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 da(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 qt(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 Dr(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 Qe=class r extends le{static defaultProps={...le.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}};var fa={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},re=class r extends le{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=fa[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)&&be.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){this.sampler=e instanceof Qe?e:this.device.createSampler(e)}copyImageData(e){let{data:t,depth:n,...i}=e;this.writeData(t,{...i,depthOrArrayLayers:i.depthOrArrayLayers??n})}computeMemoryLayout(e={}){let t=this._normalizeTextureReadOptions(e),{width:n=this.width,height:i=this.height,depthOrArrayLayers:o=this.depth}=t,{format:s,byteAlignment:a}=this;return ct.computeMemoryLayout({format:s,width:n,height:i,depth:o,byteAlignment:a})}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:o}=n;return typeof i=="number"&&(n.width=Math.max(1,Math.ceil(i))),typeof o=="number"&&(n.height=Math.max(1,Math.ceil(o))),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){let{data:t,depth:n,...i}=e,o=this._normalizeTextureWriteOptions({...i,depthOrArrayLayers:i.depthOrArrayLayers??n});return{data:t,depth:o.depthOrArrayLayers,...o}}_normalizeCopyExternalImageOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o=this.device.getExternalImageSize(e.image),s={...r.defaultCopyExternalImageOptions,...i,...o,...t};return s.width=Math.min(s.width,i.width-s.x),s.height=Math.min(s.height,i.height-s.y),s.depth=Math.min(s.depth,i.depthOrArrayLayers-s.z),s}_normalizeCopyElementImageOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o={...r.defaultCopyElementImageOptions,...i,...t};return o.width=Math.min(o.width,i.width-o.x),o.height=Math.min(o.height,i.height-o.y),o.depth=Math.min(o.depth,i.depthOrArrayLayers-o.z),o}_normalizeTextureReadOptions(e){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o={...r.defaultTextureReadOptions,...i,...t};return o.width=Math.min(o.width,i.width-o.x),o.height=Math.min(o.height,i.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,i.depthOrArrayLayers-o.z),o}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=ct.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){let t=r._omitUndefined(e),n=t.mipLevel??0,i=this._getMipLevelSize(n),o={...r.defaultTextureWriteOptions,...i,...t};o.width=Math.min(o.width,i.width-o.x),o.height=Math.min(o.height,i.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,i.depthOrArrayLayers-o.z);let s=ct.computeMemoryLayout({format:this.format,width:o.width,height:o.height,depth:o.depthOrArrayLayers,byteAlignment:this.byteAlignment}),a=s.bytesPerPixel*o.width;if(o.bytesPerRow=t.bytesPerRow??s.bytesPerRow,o.rowsPerImage=t.rowsPerImage??o.height,o.bytesPerRow<a)throw new Error(`bytesPerRow (${o.bytesPerRow}) must be at least ${a} for ${this.format}`);if(o.rowsPerImage<o.height)throw new Error(`rowsPerImage (${o.rowsPerImage}) must be at least ${o.height} for ${this.format}`);let u=this.device.getTextureFormatInfo(this.format).bytesPerPixel;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:o}=this._getMipLevelSize(t);e+=ct.computeMemoryLayout({format:this.format,width:n,height:i,depth:o,byteAlignment:1}).byteLength}return e*this.samples}static _omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}static defaultProps={...le.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"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}};var la=Ce.DEBUG_DATA_MAX_LENGTH,xe=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:o=!0,...s}=t;if(i&&i.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(i&&(s.byteLength!==void 0||s.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||i?.id||St("dynamic-buffer"),u={...s,id:a,usage:s.usage??i?.usage,indexType:s.indexType??i?.indexType};(u.usage||0)&Ce.INDEX&&!u.indexType&&(s.data instanceof Uint32Array?u.indexType="uint32":s.data instanceof Uint16Array?u.indexType="uint16":s.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=a,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:la,this._ownsBuffer=o,this._buffer=i??this.device.createBuffer({...s,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),s.data&&this._writeDebugData(s.data,s.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(o,s)=>{await e(o,s),i=new Uint8Array(o.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,o=await this._buffer.mapAndReadAsync(async(s,a)=>(i=new Uint8Array(s.slice(0)),await e(s,a)),t,n);return i&&this._writeDebugData(i,t)&&this._touch(),o}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),o=this._buffer,s=this.debugData.slice(0),{data:a,byteOffset:u,...c}=this.props,f=this.device.createBuffer({...c,byteLength:t});return n&&i>0&&this._copyBufferContents(o,f,i),this._buffer=f,this._resetDebugData(t),n&&s.byteLength>0&&this._writeDebugData(s,0),this._ownsBuffer&&o.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,o=this.device.createCommandEncoder();o.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:i}),this.device.submit(o.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),o=Math.min(n.byteLength,i.byteLength-t);return i.set(n.subarray(0,o),t),o>0}};var On={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function Yt(r){return r?Array.isArray(r)?r[0]??null:r:null}function ri(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=Yt(t);if(!n)return null;let{width:i}=Xt(n);return{width:i,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=Yt(t);return n?Xt(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=Yt(t[0]);return n?Xt(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let i=t[n],o=Yt(i);return o?Xt(o):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 o=Yt(n[i]);return o?Xt(o):null}default:return null}}function Xt(r){if(qt(r))return Dr(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 ha(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function ma(r){return ArrayBuffer.isView(r)}function Un(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 ni(r){let e=On[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function pa(r,e){return 6*r+ni(e)}function In(r){throw new Error("setTexture1DData not supported in WebGL.")}function ga(r){return Array.isArray(r)?r:[r]}function dt(r,e,t,n){let i=ga(e),o=r,s=[];for(let a=0;a<i.length;a++){let u=i[a];if(qt(u))s.push({type:"external-image",image:u,z:o,mipLevel:a});else if(ha(u))s.push({type:"texture-data",data:u,textureFormat:Un(u),z:o,mipLevel:a});else if(ma(u)&&t)s.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:o,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return s}function $n(r){let e=[];for(let t=0;t<r.length;t++)e.push(...dt(t,r[t]));return e}function kn(r){let e=[];for(let t=0;t<r.length;t++)e.push(...dt(t,r[t]));return e}function An(r){let e=[];for(let[t,n]of Object.entries(r)){let i=ni(t);e.push(...dt(i,n))}return e}function _n(r){let e=[];return r.forEach((t,n)=>{for(let[i,o]of Object.entries(t)){let s=pa(n,i);e.push(...dt(s,o))}}),e}var Ze=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=St("dynamic-texture"),i=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((o,s)=>{this.resolveReady=o,this.rejectReady=s}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(i)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?ya({...t,width:e.width,height:e.height,format:e.format}):[],i="format"in e&&e.format!==void 0,o="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 p=ri(t);return p||{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 u=ba(this.device,n,a,{format:i?e.format:void 0}),c=u.format??this.props.format,f={...this.props,...a,format:c,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(c)&&!o&&(f.usage=re.SAMPLE|re.COPY_DST);let d=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(c);if(this.device.type==="webgpu"&&d){let p=this.props.dimension==="3d"?re.SAMPLE|re.STORAGE|re.COPY_DST|re.COPY_SRC:re.SAMPLE|re.RENDER|re.COPY_DST|re.COPY_SRC;f.usage|=p}let l=this.device.getMipLevelCount(f.width,f.height),h=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?l:Math.max(1,Math.min(l,this.props.mipLevels??1)),m={...f,mipLevels:h};this._texture=this.device.createTexture(m),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!d&&be.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),be.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()):be.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof Qe?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,o=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),s=this.device.createBuffer({byteLength:o.byteLength,usage:Ce.COPY_DST|Ce.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:i},s);let a=this.device.createFence();return await a.signaled,a.destroy(),s}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,o=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),s=await this.readBuffer(e),a=await s.readAsync(0,o.byteLength);return s.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(),be.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=On[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=In(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=dt(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=$n(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=kn(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=An(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=_n(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:o,flipY:s}=t;this.texture.copyExternalImage({image:o,z:n,mipLevel:i,flipY:s});break;case"texture-data":let{data:a,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${i} uses format "${u}" 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 Fn(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&be.warn(`${this} already destroyed`)}_checkReady(){this.isReady||be.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...re.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function ya(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 In(r.data);case"2d":return dt(0,r.data,e,t);case"3d":return $n(r.data);case"2d-array":return kn(r.data);case"cube":return An(r.data);case"cube-array":return _n(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function ba(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let i=new Map;for(let f of e){let d=i.get(f.z)??[];d.push(f),i.set(f.z,d)}let o=e.some(f=>f.mipLevel>0),s=n.format,a=Number.POSITIVE_INFINITY,u=[];for(let[f,d]of i){let l=[...d].sort((w,S)=>w.mipLevel-S.mipLevel),h=l[0];if(!h||h.mipLevel!==0)throw new Error(`DynamicTexture: slice ${f} is missing mip level 0`);let m=ii(r,h);if(m.width!==t.width||m.height!==t.height)throw new Error(`DynamicTexture: slice ${f} base level dimensions ${m.width}x${m.height} do not match expected ${t.width}x${t.height}`);let p=oi(h);if(p){if(s&&s!==p)throw new Error(`DynamicTexture: slice ${f} base level format "${p}" does not match texture format "${s}"`);s=p}let y=s&&r.isTextureFormatCompressed(s)?xa(r,m.width,m.height,s):r.getMipLevelCount(m.width,m.height),g=0;for(let w=0;w<l.length;w++){let S=l[w];if(!S||S.mipLevel!==w||w>=y)break;let v=ii(r,S),T=Math.max(1,m.width>>w),b=Math.max(1,m.height>>w);if(v.width!==T||v.height!==b)break;let P=oi(S);if(P&&(s||(s=P),P!==s))break;g++,u.push(S)}a=Math.min(a,g)}let c=Number.isFinite(a)?Math.max(1,a):1;return{subresources:u.filter(f=>f.mipLevel<c),mipLevels:c,format:s,hasExplicitMipChain:o}}function oi(r){if(r.type==="texture-data")return r.textureFormat??Un(r.data)}function ii(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 xa(r,e,t,n){let{blockWidth:i=1,blockHeight:o=1}=r.getTextureFormatInfo(n),s=1;for(let a=1;;a++){let u=Math.max(1,e>>a),c=Math.max(1,t>>a);if(u<i||c<o)break;s++}return s}async function Fn(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(Fn));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(Fn)),n=Object.keys(e),i={};for(let o=0;o<n.length;o++)i[n[o]]=t[o];return i}return r}var Kt=V(R(),1),si=/^vertex-list<([^<>]+)>$/,ai=/^value-list<([^<>]+)>$/,Ca=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/;function Je(r){return si.test(r)}function et(r){return ai.test(r)}function ui(r){let e=si.exec(r),t=ai.exec(r),i=ci(r)?.elementFormat??e?.[1]??t?.[1]??r;try{Kt.vertexFormatDecoder.getVertexFormatInfo(i)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return i}function U(r){let e=ui(r),t=Je(r),n=et(r),i=ci(r),o=Kt.vertexFormatDecoder.getVertexFormatInfo(e),s=o.byteLength*(i?.listSize??1);if(!Number.isSafeInteger(s))throw new Error(`Unsupported GPUVector format ${r}`);let a=o.type,u=o.normalized,c=La(a,u);return{format:r,elementFormat:e,vertexList:t,valueList:n,fixedSizeList:!!i,...i?{listSize:i.listSize}:{},type:a,signedDataType:Ba(e,a),primitiveType:c,components:o.components,elementByteLength:o.byteLength,byteLength:s,integer:o.integer,signed:o.signed,normalized:u,...o.webglOnly?{webglOnly:!0}:{}}}function ci(r){let e=Ca.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let n=e[1];try{let i=Kt.vertexFormatDecoder.getVertexFormatInfo(n);if(!Number.isSafeInteger(t*i.components)||!Number.isSafeInteger(t*i.byteLength))return}catch{return}return{elementFormat:n,listSize:t}}function La(r,e){if(e)return"f32";switch(r){case"float32":return"f32";case"float16":return"f16";case"uint8":case"uint16":case"uint32":return"u32";case"sint8":case"sint16":case"sint32":return"i32";default:throw new Error(`Unsupported GPUVector component type ${r}`)}}function Ba(r,e){if(r==="unorm10-10-10-2")return"uint32";switch(e){case"unorm8":return"uint8";case"snorm8":return"sint8";case"unorm16":return"uint16";case"snorm16":return"sint16";default:return e}}var Mn=V(R(),1),Qt=class{buffer;format;length;byteOffset;byteStride;constructor(e){let t=Mn.vertexFormatDecoder.getVertexFormatInfo(e.format).byteLength,n=e.byteOffset??0,i=e.byteStride??t;if(Rn(e.length,"GPUDataView length"),Rn(n,"GPUDataView byteOffset"),Rn(i,"GPUDataView byteStride"),i<t)throw new Error(`GPUDataView byteStride ${i} is smaller than ${e.format} byte length ${t}`);let o=e.length===0?0:(e.length-1)*i+t,s=n+o;if(!Number.isSafeInteger(o)||!Number.isSafeInteger(s))throw new Error("GPUDataView byte range must use safe integers");if(s>e.buffer.byteLength)throw new Error("GPUDataView exceeds its backing buffer byte length");this.buffer=e.buffer,this.format=e.format,this.length=e.length,this.byteOffset=n,this.byteStride=i}get elementByteLength(){return Mn.vertexFormatDecoder.getVertexFormatInfo(this.format).byteLength}get byteLength(){return this.length===0?0:(this.length-1)*this.byteStride+this.elementByteLength}};function Rn(r,e){if(!Number.isSafeInteger(r)||r<0)throw new Error(`${e} must be a non-negative safe integer`)}var Ct=V(R(),1);function Ur(r){return!!(r&&typeof r=="object"&&r.type==="struct")}function fi(r,e){let t=Object.entries(r);if(t.length===0)throw new Error("GPUData struct format must declare at least one field");return e==="packed"?Ga(t):Da(t)}function Ga(r){let e=[],t=0,n=0;for(let[i,o]of r){let s=Ct.vertexFormatDecoder.getVertexFormatInfo(o);if(s.webglOnly)throw new Error(`Packed GPUData struct field "${i}" uses WebGL-only format ${o}`);t=di(t,Math.min(4,s.byteLength)),e.push([i,Object.freeze({format:o,byteOffset:t,byteLength:s.byteLength})]),t+=s.byteLength,n+=s.components}return Object.freeze({type:"struct",layout:"packed",fields:Object.freeze(Object.fromEntries(e)),components:n,byteStride:di(t,4),rowByteLength:t})}function Da(r){let e=Object.fromEntries(r.map(([s,a])=>[s,Oa(a)])),t=(0,Ct.makeShaderBlockLayout)(e,{layout:"wgsl-storage"}),n=[],i=0,o=0;for(let[s,a]of r){let u=Ct.vertexFormatDecoder.getVertexFormatInfo(a),c=t.fields[s].offset*4;n.push([s,Object.freeze({format:a,byteOffset:c,byteLength:u.byteLength})]),i=Math.max(i,c+u.byteLength),o+=u.components}return Object.freeze({type:"struct",layout:"wgsl-storage",fields:Object.freeze(Object.fromEntries(n)),components:o,byteStride:t.byteLength,rowByteLength:i})}function Oa(r){let e=Ct.vertexFormatDecoder.getVertexFormatInfo(r);switch(e.type){case"float32":return Or("f32",e.components);case"sint32":return Or("i32",e.components);case"uint32":return Or("u32",e.components);default:{let t=Math.ceil(e.byteLength/4);return Or("u32",t)}}}function Or(r,e){return e===1?r:`vec${e}<${r}>`}function di(r,e){return Math.ceil(r/e)*e}var Vn=class{buffer;ownsDataBuffer;constructor(e,t){this.buffer=e,this.ownsDataBuffer=t}get ownsBuffer(){return this.ownsDataBuffer}transferBufferOwnership(e){if(e.buffer!==this.buffer)throw new Error("GPUData ownership can only be transferred to the same buffer");e.ownsDataBuffer=this.ownsDataBuffer,this.ownsDataBuffer=!1}destroy(){this.ownsDataBuffer&&(this.buffer.destroy(),this.ownsDataBuffer=!1)}},Nn=class extends Vn{dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;readbackMetadata;valueOffsets;nullBitmap;valueByteLength;constructor(e){let{buffer:t,format:n,length:i,valueLength:o,stride:s,byteOffset:a=0,byteStride:u,rowByteLength:c,ownsBuffer:f=!1,readbackMetadata:d,valueOffsets:l,nullBitmap:h,valueByteLength:m,dataType:p}=e;super(t,f);let y;n?typeof n=="string"?y=n:y=fi(n,e.layout??"wgsl-storage"):y=void 0;let g=Ur(y)?y:void 0,w=typeof y=="string"?U(y):void 0;if(this.dataType=p,this.format=y,this.length=i,this.valueLength=o??i*(w?.listSize??1),this.stride=s??(w?w.components*(w.listSize??1):void 0)??g?.components??u??c??1,this.byteOffset=a,this.rowByteLength=c??g?.rowByteLength??w?.byteLength??u??this.stride,this.byteStride=u??g?.byteStride??this.rowByteLength,w?.fixedSizeList){let S=i*w.listSize;if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(S)||!Number.isSafeInteger(this.byteOffset)||this.byteOffset<0||!Number.isSafeInteger(this.byteStride)||!Number.isSafeInteger(this.rowByteLength)||!Number.isSafeInteger(this.stride))throw new Error("GPUData fixed-size-list row layout must use safe non-negative integers");if(this.valueLength!==S)throw new Error("GPUData fixed-size-list valueLength must equal its flattened row elements");if(this.stride<w.components*w.listSize)throw new Error("GPUData fixed-size-list stride cannot truncate its row components");if(this.rowByteLength<w.byteLength)throw new Error("GPUData fixed-size-list rowByteLength cannot truncate its row payload");if(this.byteStride<this.rowByteLength)throw new Error("GPUData fixed-size-list byteStride cannot overlap its row payload");let v=i===0?0:(i-1)*this.byteStride+this.rowByteLength,T=this.byteOffset+v;if(!Number.isSafeInteger(v)||!Number.isSafeInteger(T))throw new Error("GPUData fixed-size-list byte range must use safe integers");if(T>t.byteLength)throw new Error("GPUData fixed-size-list exceeds its backing buffer byte length")}if(g){if(this.rowByteLength<g.rowByteLength)throw new Error(`GPUData rowByteLength ${this.rowByteLength} is smaller than struct format row byte length ${g.rowByteLength}`);if(this.byteStride<Math.max(g.byteStride,this.rowByteLength))throw new Error(`GPUData byteStride ${this.byteStride} is smaller than its struct row layout`)}this.readbackMetadata=d,this.valueOffsets=l,this.nullBitmap=h,this.valueByteLength=m}getChild(e){if(!Ur(this.format))return null;let t=this.format.fields[e];return t?new Qt({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}getChildAt(e){if(!Ur(this.format))return null;let t=Object.values(this.format.fields)[e];return t?new Qt({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}},Lt=Nn;function Ae(r){let e=0;return Object.freeze(r.map(t=>{let n=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,n}))}var j=class{name;dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;bufferLayout;data=[];device;bufferProps;isAppendable=!1;ownsDataChunks=!0;ownedVectors=[];appendableByteLength=0;get chunks(){return Ae(this.data)}constructor(e){switch(e.type){case"buffer":{let{name:t,buffer:n,format:i,length:o,valueLength:s,byteOffset:a=0,ownsBuffer:u=!1}=e,{stride:c,byteStride:f,rowByteLength:d,listSize:l}=li(e),h=s??o*(l??1);this.name=t,this.dataType=e.dataType,this.format=i,this.length=o,this.valueLength=h,this.stride=c,this.byteOffset=a,this.byteStride=f,this.rowByteLength=d,this.data.push(new Lt({buffer:n,format:i,length:o,valueLength:h,stride:c,byteOffset:a,byteStride:f,rowByteLength:d,ownsBuffer:u,dataType:e.dataType}));return}case"interleaved":{let{name:t,buffer:n,format:i,length:o,valueLength:s,byteOffset:a=0,byteStride:u,attributes:c,ownsBuffer:f=!1}=e,d=i?U(i):void 0,l=s??o*(d?.listSize??1),h=d?.fixedSizeList?d.components*d.listSize:u,m=d?.fixedSizeList?d.byteLength:u;this.name=t,this.dataType=e.dataType,this.format=i,this.length=o,this.valueLength=l,this.stride=h,this.byteOffset=a,this.byteStride=u,this.rowByteLength=m,this.bufferLayout={name:t,byteStride:u,attributes:c},this.data.push(new Lt({buffer:n,format:i,length:o,valueLength:l,stride:h,byteOffset:a,byteStride:u,rowByteLength:m,ownsBuffer:f,dataType:e.dataType}));return}case"data":{let t=e.format??Ua(e.data),n=t?U(t):void 0,{name:i,data:o,stride:s=o[0]?.stride??(n?n.components*(n.listSize??1):1),valueLength:a=o.reduce((l,h)=>l+h.valueLength,0),byteStride:u=o[0]?.byteStride??n?.byteLength,rowByteLength:c=o[0]?.rowByteLength??n?.byteLength,bufferLayout:f,ownsData:d=!1}=e;if(u===void 0||c===void 0)throw new Error("GPUVector requires format or explicit byte layout metadata");t&&Ia(o,t),this.name=i,this.dataType=e.dataType,this.format=t,this.length=o.reduce((l,h)=>l+h.length,0),this.valueLength=a,this.stride=s,this.byteOffset=o.length===1?o[0].byteOffset:0,this.byteStride=u,this.rowByteLength=c,this.bufferLayout=f,this.ownsDataChunks=d,this.data.push(...o);return}case"appendable":{let{name:t,device:n,format:i,valueLength:o=0,bufferProps:s}=e,{stride:a,byteStride:u,rowByteLength:c}=li(e);this.name=t,this.dataType=e.dataType,this.format=i,this.length=0,this.valueLength=o,this.stride=a,this.byteOffset=0,this.byteStride=u,this.rowByteLength=c,this.device=n,this.bufferProps=s,this.isAppendable=!0;return}}}get ownsBuffer(){return this.ownsDataChunks&&this.data.some(e=>e.ownsBuffer)||this.ownedVectors.some(e=>e.ownsBuffer)}get capacityRows(){return this.isAppendable?this.length:void 0}get appendedByteLength(){return this.appendableByteLength}addData(e){if(this.format&&e.format!==this.format)throw new Error("GPUVector.addData() requires matching formats");if(e.byteStride!==this.byteStride)throw new Error("GPUVector.addData() requires matching byteStride");if(e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.addData() requires matching rowByteLength");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this}appendDataChunk(e,t=this.appendableByteLength+e.buffer.byteLength){if(!this.isAppendable)throw new Error("GPUVector.appendDataChunk() requires appendable vector storage");if(this.format&&e.format!==this.format)throw new Error("GPUVector.appendDataChunk() requires matching formats");if(e.byteStride!==this.byteStride||e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.appendDataChunk() requires matching byte layout metadata");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this.appendableByteLength=t,this}resetLastBatch(){if(!this.isAppendable)throw new Error("GPUVector.resetLastBatch() requires appendable vector storage");for(let e of this.data.splice(0))e.destroy();return this.length=0,this.valueLength=0,this.appendableByteLength=0,this}retainOwnedVectors(e){return this.ownedVectors.push(...e),this}transferBufferOwnership(e){let t=this.data[0],n=e.data[0];if(!t||!n||t.buffer!==n.buffer)throw new Error("GPUVector ownership can only be transferred to the same buffer");t.transferBufferOwnership(n)}destroy(){if(this.ownsDataChunks)for(let e of this.data)e.destroy();for(let e of this.ownedVectors.splice(0))e.destroy()}};function li(r){let e=r.format?U(r.format):void 0,t=r.rowByteLength??(e?.fixedSizeList?e.byteLength:r.byteStride)??e?.byteLength;if(t===void 0)throw new Error("GPUVector requires format or explicit rowByteLength");return{stride:r.stride??(e?e.components*(e.listSize??1):1),byteStride:r.byteStride??t,rowByteLength:t,...e?.listSize?{listSize:e.listSize}:{}}}function Ua(r){return r[0]?.format}function Ia(r,e){if(r.find(n=>n.format!==e))throw new Error("GPUVector data chunks must share the declared format")}var zn=V(R(),1);var Zt=V(R(),1);var Jt=class{buffer;format;length;valueLength;byteOffset;byteStride;rowByteLength;valueOffsets;nullBitmap;constructor(e){let t=U(e.format),n=ArrayBuffer.isView(e.buffer)?e.buffer:void 0;this.buffer=n?n.buffer:e.buffer,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength??e.length*(t.listSize??1);let i=e.byteOffset??0;this.byteOffset=(n?.byteOffset??0)+i,this.rowByteLength=e.rowByteLength??t.byteLength,this.byteStride=e.byteStride??this.rowByteLength,this.valueOffsets=e.valueOffsets,this.nullBitmap=e.nullBitmap;let o=t.vertexList||t.valueList,s=o?this.valueLength:this.length;(0,Zt.assert)([this.length,this.valueLength,i,this.rowByteLength,this.byteStride].every(a=>Number.isSafeInteger(a)&&a>=0)),(0,Zt.assert)(this.rowByteLength>=t.byteLength&&this.byteStride>=this.rowByteLength),(0,Zt.assert)(o||this.valueLength===this.length*(t.listSize??1)),(0,Zt.assert)(i+(s?(s-1)*this.byteStride+this.rowByteLength:0)<=e.buffer.byteLength)}};var hi=V(R(),1),we=class{name;format;data;length;valueLength;constructor(e){(0,hi.assert)(e.data.every(t=>t.format===e.format)),this.name=e.name??"",this.format=e.format,this.data=Object.freeze([...e.data]),this.length=this.data.reduce((t,n)=>t+n.length,0),this.valueLength=this.data.reduce((t,n)=>t+n.valueLength,0)}};var er=class{compare;values=[];constructor(e){this.compare=e}peek(){return this.values[0]}push(e){let t=this.values.length;for(this.values.push(e);t>0;){let n=Math.floor((t-1)/2);if(this.compare(this.values[n],e)<=0)break;this.values[t]=this.values[n],t=n}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let n=0;for(;n*2+1<this.values.length;){let i=n*2+1;if(i+1<this.values.length&&this.compare(this.values[i+1],this.values[i])<0&&i++,this.compare(t,this.values[i])<=0)break;this.values[n]=this.values[i],n=i}this.values[n]=t}return e}};var tt=V(R(),1);function bi(r){let e=vi(r.nodes),t=Si(e,r.buffers.values()),n=Ei(e,r.textures.values()),i=new Map,o=new Map,s=[];try{for(let a of t){a.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(a)}`,byteLength:a.byteLength,usage:a.usage});for(let u of a.handles)i.set(u,a.buffer)}for(let a of n){a.texture=r.device.createTexture({...a.descriptor,id:`${r.id}-transient-texture-${n.indexOf(a)}`});for(let u of a.handles)o.set(u,a.texture)}for(let a of e)s.push({node:a,executable:a.compile({device:r.device})})}catch(a){for(let u of s)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of n)u.texture?.destroy();throw a}return wi(r,e,s,i,o,t,n)}async function xi(r){let e=vi(r.nodes),t=Si(e,r.buffers.values()),n=Ei(e,r.textures.values()),i=new Map,o=new Map;try{for(let h of t){h.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(h)}`,byteLength:h.byteLength,usage:h.usage});for(let m of h.handles)i.set(m,h.buffer)}for(let h of n){h.texture=r.device.createTexture({...h.descriptor,id:`${r.id}-transient-texture-${n.indexOf(h)}`});for(let m of h.handles)o.set(m,h.texture)}let s=tt.PipelineFactory.beginAsyncCompilation(r.device),a=e.map(async h=>({node:h,executable:h.compileAsync?await h.compileAsync({device:r.device}):h.compile({device:r.device})}));tt.PipelineFactory.endAsyncCompilation(r.device,s);let[u,c]=await Promise.all([Promise.allSettled(a),Promise.allSettled(s)]),f=[],d=c.find(h=>h.status==="rejected"),l=d?.status==="rejected"?d.reason:void 0;for(let h of u)h.status==="fulfilled"?f.push(h.value):l??=h.reason;if(l){for(let h of f)h.executable.destroy?.();throw l}return wi(r,e,f,i,o,t,n)}catch(s){for(let a of t)a.buffer?.destroy();for(let a of n)a.texture?.destroy();throw s}}function wi(r,e,t,n,i,o,s){let a=Array.from(r.buffers.values()),u=a.filter(E=>!E.transient),c=a.filter(E=>E.transient),f=Bt(u.map(E=>E.byteLength),"imported buffer capacities"),d=Bt(c.map(E=>E.byteLength),"logical transient buffer capacities"),l=ft(f,d,"logical buffer capacities"),h=Bt(o.map(E=>E.byteLength),"physical transient buffer capacities"),m=Math.max(0,d-h),p=Array.from(r.textures.values()),y=p.filter(E=>!E.transient),g=p.filter(E=>E.transient),w=Bt(y.map(qn),"imported texture estimates"),S=Bt(g.map(qn),"logical transient texture estimates"),v=ft(w,S,"logical texture estimates"),T=Bt(s.map(E=>E.byteLength),"physical transient texture estimates"),b=Math.max(0,S-T),P={nodeOrder:e.map(E=>E.id),importedBufferCount:u.length,importedBufferBytes:f,logicalBufferCount:a.length,logicalBufferBytes:l,logicalTransientBufferCount:c.length,physicalTransientBufferCount:o.length,logicalTransientBytes:d,physicalTransientBytes:h,reusedTransientBytes:m,reusePercentage:d>0?m/d*100:0,importedTextureCount:y.length,importedTextureBytes:w,logicalTextureCount:p.length,logicalTextureBytes:v,logicalTransientTextureCount:g.length,physicalTransientTextureCount:s.length,logicalTransientTextureBytes:S,physicalTransientTextureBytes:T,reusedTransientTextureBytes:b,textureReusePercentage:S>0?b/S*100:0,logicalResourceBytes:ft(l,v,"logical resource estimates"),physicalTransientResourceBytes:ft(h,T,"physical transient resource estimates")},B=ka(r.device,a,e);return{device:r.device,id:r.id,buffers:new Map(r.buffers),textures:new Map(r.textures),externalTextures:new Map(r.externalTextures),compiledNodes:t,transientBuffers:n,transientTextures:i,bufferTransientAllocations:o,textureTransientAllocations:s,stats:P,preflight:B}}function $a(r){if("buffer"in r){let t=r.buffer,n="buffer"in t?t:void 0;return Object.freeze({id:n?n.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:n?.byteOffset??0,byteLength:n?n.length===0?0:(n.length-1)*n.byteStride+n.rowByteLength:t.byteLength,...n?{format:n.format,length:n.length}:{}})}let e="texture"in r?r.texture:r.externalTexture;return Object.freeze({id:"texture"in e?e.texture.id:e.id,kind:"externalTexture"in r?"external-texture":"texture",usage:r.usage,width:e.width,height:e.height,..."texture"in e?{baseMipLevel:e.baseMipLevel,baseArrayLayer:e.baseArrayLayer,mipLevelCount:e.mipLevelCount,arrayLayerCount:e.arrayLayerCount,aspect:e.aspect}:{},..."format"in e?{format:e.format,depth:e.depth}:{}})}function ka(r,e,t){let n=t.map(a=>{let u=a.workload??{};return Object.freeze({id:a.id,...a.description===void 0?{}:{description:a.description},type:a.type,resources:Object.freeze((a.resources??[]).map($a)),...u.operation?{operation:u.operation}:{},...u.variant?{variant:u.variant}:{},...a.publication?{publication:Object.freeze({...a.publication})}:{},...a.condition?{condition:Object.freeze(a.condition.source==="cpu"?{id:a.condition.id,source:"cpu",mode:"skip"}:{id:a.condition.id,source:"gpu",mode:"indirect",bufferId:a.condition.buffer.id,byteOffset:a.condition.byteOffset??0})}:{},commandCount:u.commandCount??0,maximumWorkgroupCount:u.maximumWorkgroupCount??0,maximumInvocationCount:u.maximumInvocationCount??0,readByteLength:u.readByteLength??0,writeByteLength:u.writeByteLength??0})}),i=e.reduce((a,u)=>Math.max(a,u.byteLength),0),o=t.reduce((a,u)=>{for(let c of u.resources??[])rt(c)&&(c.usage==="storage-read"||c.usage==="storage-write"||c.usage==="storage-read-write")&&(a=Math.max(a,jn(c.buffer).size));return a},0),s=a=>n.reduce((u,c)=>{let f=c[a];return typeof f=="number"?ft(u,f,"workload estimates"):u},0);return Object.freeze({nodes:Object.freeze(n),annotatedNodeCount:t.filter(a=>a.workload!==void 0).length,conditionalNodeCount:t.filter(a=>a.condition!==void 0).length,commandCount:s("commandCount"),maximumWorkgroupCount:s("maximumWorkgroupCount"),maximumInvocationCount:s("maximumInvocationCount"),readByteLength:s("readByteLength"),writeByteLength:s("writeByteLength"),largestBufferByteLength:i,largestStorageBufferBindingByteLength:o,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:i<=r.limits.maxBufferSize&&o<=r.limits.maxStorageBufferBindingSize})}function Te(r){return"buffer"in r?r.buffer:r}function _e(r){return"texture"in r?r.texture:r}function rt(r){return"buffer"in r}function tr(r){return"texture"in r}function Ti(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>rt(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let n=e[t];for(let i=t+1;i<e.length;i++){let o=e[i];if(n.buffer===o.buffer||Te(n.buffer)!==Te(o.buffer)||!Hn(n.usage)&&!Hn(o.usage))continue;let s=jn(n.buffer),a=jn(o.buffer);if(s.offset<a.offset+a.size&&a.offset<s.offset+s.size){let u=Te(n.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${mi(s)} and ${mi(a)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function jn(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,n=r.byteOffset-t,i=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:n+Math.max(i,r.rowByteLength)}}function mi(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Aa(r){return r==="storage-read"||r==="storage-read-write"||r==="uniform"||r==="copy-source"||r==="indirect"||r==="vertex"||r==="index"}function Hn(r){return r==="storage-write"||r==="storage-read-write"||r==="copy-destination"}function pi(r){return r==="sampled"||r==="storage-read"||r==="storage-read-write"||r==="render-attachment"||r==="copy-source"}function Wn(r){return r==="storage-write"||r==="storage-read-write"||r==="render-attachment"||r==="copy-destination"}function vi(r){let e=new Map(r.map(d=>[d.id,d])),t=new Map,n=new Map,i=new Map,o=new Map;for(let d of r){let l=new Set(d.dependsOn??[]);for(let h of l)if(!e.has(h))throw new Error(`GPUCommandGraph node "${d.id}" depends on missing node "${h}"`);for(let h of d.resources??[])if(rt(h)){let m=Te(h.buffer);if(Aa(h.usage)){let p=n.get(m);p&&l.add(p);let y=i.get(m)??new Set;y.add(d.id),i.set(m,y)}if(Hn(h.usage)){let p=n.get(m);p&&l.add(p);for(let y of i.get(m)??[])y!==d.id&&l.add(y);i.set(m,new Set),n.set(m,d.id)}}else if(tr(h)){let m=_e(h.texture),p=o.get(m)??[];for(let y of p)y.nodeId!==d.id&&_a(y.resource,h)&&(pi(h.usage)&&Wn(y.resource.usage)||Wn(h.usage)&&(pi(y.resource.usage)||Wn(y.resource.usage)))&&l.add(y.nodeId);p.push({nodeId:d.id,resource:h}),o.set(m,p)}l.delete(d.id),t.set(d.id,l)}let s=r.map(()=>[]),a=new Map(r.map((d,l)=>[d.id,l])),u=r.map(d=>t.get(d.id).size);for(let[d,l]of r.entries())for(let h of t.get(l.id))s[a.get(h)].push(d);let c=u.flatMap((d,l)=>d===0?[l]:[]),f=[];for(;c.length;){let d=[];for(let l of c){f.push(r[l]);for(let h of s[l])--u[h]===0&&d.push(h)}c=d.sort((l,h)=>l-h)}if(f.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return f}function _a(r,e){let t=_e(r.texture),n=_e(e.texture);if(t!==n)return!1;let i=gi(r.texture),o=gi(e.texture);return Fa(i.aspect,o.aspect)&&yi(i.baseMipLevel,i.mipLevelCount,o.baseMipLevel,o.mipLevelCount)&&yi(i.baseArrayLayer,i.arrayLayerCount,o.baseArrayLayer,o.arrayLayerCount)}function gi(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function Fa(r,e){return r==="all"||e==="all"||r===e}function yi(r,e,t,n){return r<t+n&&t<r+e}function Si(r,e){let t=Pi(r,c=>rt(c)?Te(c.buffer):null),n=new Map;r.forEach((c,f)=>{if(!c.retainedBuffers?.length)return;let d=n.get(c.retainedBuffers);d?d.lastUse=f:n.set(c.retainedBuffers,{firstUse:f,lastUse:f})});for(let[c,f]of n)for(let d of c){if(!d.transient)continue;let l=t.get(d);t.set(d,{firstUse:Math.min(l?.firstUse??f.firstUse,f.firstUse),lastUse:Math.max(l?.lastUse??f.lastUse,f.lastUse)})}let i=[],o=Array.from(e).filter(c=>c.transient).map(c=>({buffer:c,lifetime:t.get(c)})).sort((c,f)=>(c.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(f.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),s=new er((c,f)=>c.allocation.lastUse-f.allocation.lastUse||c.index-f.index),a=new Map,u=c=>{let f=c&(tt.Buffer.MAP_READ|tt.Buffer.MAP_WRITE),d=a.get(f);return d||(d=new er((l,h)=>l.allocation.byteLength-h.allocation.byteLength||l.index-h.index),a.set(f,d)),d};for(let{buffer:c,lifetime:f}of o){if(!f)continue;for(;s.peek()&&s.peek().allocation.lastUse<f.firstUse;){let h=s.pop();u(h.allocation.usage).push(h)}let d=u(c.usage).pop();d||(d={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:i.length},i.push(d.allocation));let{allocation:l}=d;l.byteLength=Math.max(l.byteLength,c.byteLength),l.usage|=c.usage,l.lastUse=f.lastUse,l.handles.push(c),s.push(d)}return i}function Ei(r,e){let t=Pi(r,o=>tr(o)?_e(o.texture):null),n=[],i=Array.from(e).filter(o=>o.transient).map(o=>({texture:o,lifetime:t.get(o)})).sort((o,s)=>(o.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(s.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:o,lifetime:s}of i){if(!s)continue;let a=n.find(u=>u.lastUse<s.firstUse&&Ma(u.descriptor,o));a||(a={descriptor:Ra(o),byteLength:qn(o),lastUse:-1,handles:[]},n.push(a)),a.descriptor.usage|=o.usage,a.lastUse=s.lastUse,a.handles.push(o)}return n}function Pi(r,e){let t=new Map;return r.forEach((n,i)=>{for(let o of n.resources??[]){let s=e(o);if(!s||!("transient"in s)||!s.transient)continue;let a=t.get(s);a?a.lastUse=i:t.set(s,{firstUse:i,lastUse:i})}}),t}function Ra(r){return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:r.dimension,depth:r.depth,mipLevels:r.mipLevels,samples:r.samples}}function Ma(r,e){return r.format===e.format&&r.width===e.width&&r.height===e.height&&r.dimension===e.dimension&&r.depth===e.depth&&r.mipLevels===e.mipLevels&&r.samples===e.samples}function qn(r){let e=0;for(let n=0;n<r.mipLevels;n++)e=ft(e,tt.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>n),height:r.dimension==="1d"?1:Math.max(1,r.height>>n),depth:r.dimension==="3d"?Math.max(1,r.depth>>n):r.depth,byteAlignment:1}).byteLength,`texture "${r.id}" mip estimates`);let t=e*r.samples;if(!Number.isSafeInteger(t))throw new Error(`GPUCommandGraph texture "${r.id}" byte estimate exceeds safe integer range`);return t}function ft(r,e,t){let n=r+e;if(!Number.isSafeInteger(n))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return n}function Bt(r,e){return r.reduce((t,n)=>ft(t,n,e),0)}var Fe=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,n,i){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=n,this.defaultBuffer=i}},Ge=class{buffer;format;length;byteOffset;byteStride;rowByteLength;constructor(e,t){this.buffer=e,this.format=t.format,this.length=t.length,this.byteOffset=t.byteOffset,this.byteStride=t.byteStride,this.rowByteLength=t.rowByteLength}},D=class{chunks;id;name;format;length;valueLength;stride;byteStride;rowByteLength;data;constructor(e){if(this.id=e.id,this.name=e.name,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength,this.stride=e.stride,this.byteStride=e.byteStride,this.rowByteLength=e.rowByteLength,e.data.some(t=>t.format!==e.format)||e.data.reduce((t,n)=>t+n.length,0)!==e.length)throw new Error(`${e.id} length must equal its ordered source chunks, with matching formats`);this.data=Object.freeze([...e.data]),this.chunks=Ae(this.data)}},ve=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,n,i,o=!1){this.graph=e,this.id=t.id,this.format=t.format,this.width=t.width,this.height=t.height,this.usage=t.usage,this.dimension=t.dimension,this.depth=t.depth,this.mipLevels=t.mipLevels,this.samples=t.samples,this.transient=n,this.frameScoped=o,this.defaultTexture=i}},nt=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},De=class{texture;format;dimension;aspect;baseMipLevel;mipLevelCount;baseArrayLayer;arrayLayerCount;width;height;depth;constructor(e,t){this.texture=e,this.format=e.format,this.dimension=t.dimension,this.aspect=t.aspect,this.baseMipLevel=t.baseMipLevel,this.mipLevelCount=t.mipLevelCount,this.baseArrayLayer=t.baseArrayLayer,this.arrayLayerCount=t.arrayLayerCount,this.width=t.width,this.height=t.height,this.depth=t.depth}};function Yn(r,e){switch(e.type){case"compute":{let{type:t,...n}=e;r.addComputePass(n);return}case"render":{let{type:t,...n}=e;r.addRenderPass(n);return}case"copy":{let{type:t,...n}=e;r.addCopyPass(n);return}}}function Re(r,e){for(let t of e)Yn(r,t)}function N(r){return{...r,type:"compute"}}var Va=4,Gt=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){Oi(e.budget),this.plan=e.plan,this.nodeCount=e.plan.nodeCount,this.budget=Object.freeze({...e.budget}),this.encodeNodeRange=e.encodeNodeRange}get completed(){return this.nextStepIndex>=this.plan.stepCount}get progress(){return this.plan.stepCount===0?1:this.nextStepIndex/this.plan.stepCount}get publishedProgress(){return this.currentPublishedProgress}encodeNext(e,t){if(this.completed)throw new Error("GPUCommandGraph execution has already completed");let n=this.plan.steps[this.nextStepIndex],i=this.encodeNodeRange(e,t,n.firstNodeIndex,n.nextNodeIndex);return this.nextStepIndex++,n.publishable&&(this.currentPublishedProgress=this.progress),{...n,encoding:i,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function $r(r,e,t={}){Oi(e);let n=t.latencyPriority??"normal",i=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(n))throw new Error(`GPUCommandGraph execution latency priority "${n}" is invalid`);if(!["final","progressive"].includes(i))throw new Error(`GPUCommandGraph execution publication policy "${i}" is invalid`);let o=r.nodes,s=[],a=0;for(;a<o.length;){let c=a,f=Ci();for(;a<o.length;){let h=Li(f,o[a]);if(a>c&&Bi(h,e)||(f=h,a++,i==="progressive"&&o[a-1].publication)||Na(f,e))break}let d=Object.freeze(i==="progressive"?o.slice(c,a).flatMap(h=>h.publication?[h.publication]:[]):[]),l=a===o.length;s.push(Object.freeze({stepIndex:s.length,firstNodeIndex:c,nextNodeIndex:a,...f,exceedsBudget:Bi(f,e),latencyPriority:n,publications:d,publishable:l||d.length>0}))}let u=o.reduce((c,f)=>Li(c,f),Ci());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:s.length,oversizedStepCount:s.filter(c=>c.exceedsBudget).length,latencyPriority:n,publicationPolicy:i,publicationCount:s.reduce((c,f)=>c+f.publications.length,0),steps:Object.freeze(s)})}function Ci(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function Li(r,e){return{nodeCount:r.nodeCount+1,commandCount:r.commandCount+e.commandCount,maximumInvocationCount:r.maximumInvocationCount+e.maximumInvocationCount,readByteLength:r.readByteLength+e.readByteLength,writeByteLength:r.writeByteLength+e.writeByteLength,conditionalNodeCount:r.conditionalNodeCount+(e.condition?1:0)}}function Bi(r,e){return r.maximumInvocationCount>e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>e.maximumWriteByteLength}function Na(r,e){return r.maximumInvocationCount>=e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>=e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>=e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>=e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>=e.maximumWriteByteLength}function Oi(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,n]of e)if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function za(r,e,t,n){let i=0;return{computePass:new Proxy(r,{get(s,a){if(a==="dispatch")return()=>{if(i>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`);i++,s.dispatchIndirect(e,t)};if(a==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(s,a,s);return typeof u=="function"?u.bind(s):u}}),assertDispatched:()=>{if(i!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`)}}}var Dt=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,n=e.filter(a=>a.stats.type==="compute"&&a.stats.condition?.outcome!=="skipped").length,i,o,s){this.readResource=s,this.nodes=e,this.canReadGPUTimings=e.some(c=>c.timestamp!==void 0);let a=e.filter(c=>c.stats.condition?.outcome!=="skipped"),u=a.filter(c=>c.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:i,cpuEncodeEndTimeMilliseconds:o,nodeCount:a.length,skippedNodeCount:e.length-a.length,computePassCount:n,coalescedComputeNodeCount:u-n,timestampedNodeCount:e.filter(c=>c.timestamp!==void 0).length,nodes:e.map(c=>c.stats)}}async readTimings(){let e=await Promise.all(this.nodes.map(async({stats:s,timestamp:a})=>{if(!a)return{...s};let{querySet:u,snapshot:c,beginIndex:f,endIndex:d}=a;if(u.device.type!=="webgpu")return{...s,gpuTimeMilliseconds:await u.readTimestampDuration(f,d)};let l=await(c??u).readResults({firstQuery:f,queryCount:d-f+1}),h=l[0],m=l[l.length-1];return{...s,gpuStartTimeMilliseconds:Number(h)/1e6,gpuEndTimeMilliseconds:Number(m)/1e6,gpuTimeMilliseconds:Number(m-h)/1e6}})),t=e.filter(s=>s.gpuTimeMilliseconds!==void 0),n=e.filter(s=>s.gpuStartTimeMilliseconds!==void 0),o=this.nodes.flatMap(s=>s.timestamp?.snapshot?.clockCorrelation?[s.timestamp.snapshot.clockCorrelation]:[]).sort((s,a)=>s.uncertaintyMilliseconds-a.uncertaintyMilliseconds)[0];return{...o?{clockCorrelation:o}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...n.length>0?{gpuStartTimeMilliseconds:Math.min(...n.map(s=>s.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...n.map(s=>s.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((s,a)=>s+(a.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},Kn=class{device;id;autotuner;buffers=new Map;textures=new Map;externalTextures=new Map;importedBufferHandles=new Map;dynamicBufferHandles=new Map;nodes=[];nodeIds=new Set;compiled=!1;constructor(e,t={}){Ir(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),Di(e,this.device),t&&Ui(t,e,this.device);let n=this.addBuffer(new Fe(this,e,!1,t));if(t){let i=or(t);this.importedBufferHandles.has(i)||this.importedBufferHandles.set(i,n),t instanceof xe&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,n)}return n}createTransientBuffer(e){return this.assertMutable(),Di(e,this.device),this.addBuffer(new Fe(this,e,!0))}createDataView(e,t){this.assertBuffer(e);let n=U(t.format),i=t.byteOffset??0,o=t.rowByteLength??n.byteLength,s=t.byteStride??o;return Xa(e,{length:t.length,byteOffset:i,byteStride:s,rowByteLength:o}),new Ge(e,{format:t.format,length:t.length,byteOffset:i,byteStride:s,rowByteLength:o})}importGPUData(e,t){return this.importGPUDataView(e,t)}importGPUVector(e,t){if(t.bufferLayout)throw new Error(`GPUCommandGraph import "${e}" does not accept interleaved GPUVector data`);let n=t.format??t.data[0]?.format;if(!n)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(Je(n)||et(n))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let i=U(n),o=t.data.map((s,a)=>{if(s.format!==n)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${a}`;return this.importGPUDataView(u,s)});return new D({id:e,name:t.name??e,format:n,length:t.length,valueLength:t.valueLength??t.data.reduce((s,a)=>s+a.valueLength,0),stride:t.stride??t.data[0]?.stride??i.components*(i.listSize??1),byteStride:t.byteStride??o[0]?.byteStride??i.byteLength,rowByteLength:t.rowByteLength??o[0]?.rowByteLength??i.byteLength,data:o})}importTexture(e,t){this.assertMutable();let n=Xn(e,this.device);return t&&Zn(t,n,this.device),this.addTexture(new ve(this,n,!1,t))}importFrameTexture(e){this.assertMutable();let t=Xn(e,this.device);return this.addTexture(new ve(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),qa(e,this.device),this.addExternalTexture(new nt(this,e))}createTransientTexture(e){this.assertMutable();let t=Xn(e,this.device);return this.addTexture(new ve(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let n=Ya(e,t);return new De(e,n)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)Re(this,e.getCommandNodes(this));else if("type"in e)Yn(this,e);else for(let t of e)this.add(t)}addComputePass(e){this.addNode({...e,type:"compute"})}addRenderPass(e){e.attachments&&this.validateRenderAttachments(e.id,e.attachments);let t=e.attachments?[...e.attachments.colorAttachments.map(n=>({texture:n,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(n=>n!==null).map(n=>({texture:n,usage:"render-attachment"})),...e.attachments.depthStencilAttachment?[{texture:e.attachments.depthStencilAttachment,usage:"render-attachment"}]:[]]:[];this.addNode({...e,resources:[...e.resources??[],...t],type:"render"})}addCopyPass(e){this.addNode({...e,type:"copy"})}compile(){return this.assertMutable(),Ir(this.device,"compilation"),this.compiled=!0,new lt(bi({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}async compileAsync(){return this.assertMutable(),Ir(this.device,"compilation"),this.compiled=!0,new lt(await xi({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}addNode(e){if(this.device.type!=="webgpu"&&e.type!=="render")throw new Error("WebGL graphs support render passes only");if(this.assertMutable(),!e.id)throw new Error("GPUCommandGraph node id is required");if(this.nodeIds.has(e.id))throw new Error(`GPUCommandGraph node id "${e.id}" is already in use`);for(let[t,n]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof n!="string"||!n)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be a nonnegative safe integer`);if(e.condition){if(!e.condition.id)throw new Error(`GPUCommandGraph node "${e.id}" condition id is required`);if(e.condition.source==="cpu"){if(typeof e.condition.evaluate!="function")throw new Error(`GPUCommandGraph node "${e.id}" CPU condition requires an evaluate function`)}else{let t=e.condition;if(e.type!=="compute"||t.mode!=="indirect")throw new Error(`GPUCommandGraph node "${e.id}" GPU conditions require an indirect compute node`);if(!t.buffer)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition requires an indirect command buffer`);this.assertBuffer(t.buffer);let n=t.byteOffset??0;if(!Number.isSafeInteger(n)||n<0||n%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(n+3*Va>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(i=>rt(i)&&Te(i.buffer)===t.buffer&&i.usage==="indirect")||(e={...e,resources:[...e.resources??[],{buffer:t.buffer,usage:"indirect"}]})}}if(e.publication){if(e.condition)throw new Error(`GPUCommandGraph node "${e.id}" cannot combine conditional execution with a publication boundary`);if(!e.publication.id)throw new Error(`GPUCommandGraph node "${e.id}" publication id is required`);if(!["partial","complete"].includes(e.publication.completeness))throw new Error(`GPUCommandGraph node "${e.id}" publication completeness is invalid`)}for(let t of e.resources??[])if(rt(t)){let n=Te(t.buffer);this.assertBuffer(n),Qa(n,t.usage)}else if(tr(t)){let n=_e(t.texture);if(this.assertTexture(n),Za(n,t.usage),Ja(t.texture,t.usage),this.device.type==="webgl"&&t.usage==="sampled"&&t.texture instanceof De&&!Ii(t.texture))throw new Error("WebGL sampled textures require a full-resource view")}else{if(this.assertExternalTexture(t.externalTexture),t.usage!=="sampled")throw new Error("GPUCommandGraph external textures support sampled access only");if(e.type!=="render")throw new Error("GPUCommandGraph external textures can be sampled only by render nodes")}Ti(e),this.nodeIds.add(e.id),this.nodes.push(e)}addBuffer(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.buffers.set(e.id,e),e}addTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.textures.set(e.id,e),e}addExternalTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.externalTextures.set(e.id,e),e}importGPUDataView(e,t){if(!t.format)throw new Error(`GPUCommandGraph import "${e}" requires GPUData.format`);let n=or(t.buffer),i={byteLength:Wa(t),usage:n.usage},o=t.buffer instanceof xe?this.getDynamicBufferHandle(t.buffer,i):this.getImportedBufferHandle(n,i);return o||(o=this.importBuffer({id:e,byteLength:n.byteLength,usage:n.usage},t.buffer),t.buffer instanceof xe?this.dynamicBufferHandles.set(t.buffer,o):this.importedBufferHandles.set(n,o)),this.createDataView(o,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let n=this.dynamicBufferHandles.get(e);if(n?.defaultBuffer===e&&rr(n,t))return n;this.dynamicBufferHandles.delete(e);for(let i of this.buffers.values())if(i.defaultBuffer===e&&rr(i,t))return this.dynamicBufferHandles.set(e,i),i}getImportedBufferHandle(e,t){let n=this.importedBufferHandles.get(e);if(n?.defaultBuffer&&or(n.defaultBuffer)===e&&rr(n,t))return n;this.importedBufferHandles.delete(e);for(let[i,o]of this.dynamicBufferHandles)if(i.buffer===e&&rr(o,t))return this.importedBufferHandles.set(e,o),o;for(let i of this.buffers.values())if(i.defaultBuffer===e&&rr(i,t))return this.importedBufferHandles.set(e,i),i}assertBuffer(e){if(e.graph!==this||this.buffers.get(e.id)!==e)throw new Error(`Graph buffer "${e.id}" does not belong to ${this.id}`)}assertTexture(e){if(e.graph!==this||this.textures.get(e.id)!==e)throw new Error(`Graph texture "${e.id}" does not belong to ${this.id}`)}assertExternalTexture(e){if(e.graph!==this||this.externalTextures.get(e.id)!==e)throw new Error(`Graph external texture "${e.id}" does not belong to ${this.id}`)}assertMutable(){if(this.compiled)throw new Error(`GPUCommandGraph "${this.id}" has already been compiled`)}validateRenderAttachments(e,t){if(t.colorAttachments.length===0&&!t.depthStencilAttachment)throw new Error(`GPUCommandGraph render node "${e}" requires at least one attachment`);let n=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let s of n)if(this.assertTexture(s.texture),s.dimension!=="2d"||s.mipLevelCount!==1||s.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[i,...o]=n;for(let s of o)if(s.width!==i.width||s.height!==i.height||s.texture.samples!==i.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let n=t.resolveTargets;if(n){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(n.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let i=0;i<n.length;i++){let o=n[i];if(!o)continue;let s=t.colorAttachments[i];if(this.assertTexture(o.texture),s.texture.samples<=1||o.texture.samples!==1||s.format!==o.format||s.width!==o.width||s.height!==o.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${i} must match a multisampled source and be single-sampled`);if(o.dimension!=="2d"||o.aspect!=="all"||o.mipLevelCount!==1||o.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" resolve targets must be single-mip, single-layer 2d color views`)}}}},lt=class{device;id;stats;preflight;capabilities;buffers;textures;externalTextures;compiledNodes;activeImportedBufferHandles=new Set;writableImportedBufferHandles=new Set;activeImportedTextureHandles=new Set;writableImportedTextureHandles=new Set;transientBuffers;transientTextures;bufferTransientAllocations;textureTransientAllocations;cachedTextureViews=[];cachedFramebuffers=[];lastFrameIds=new Map;lastExternalTextureFrameIds=new Map;consumedExternalTextures=new WeakSet;destroyed=!1;get[Symbol.toStringTag](){return"CompiledGPUCommandGraph"}toString(){let e=this.destroyed?"destroyed":"active";return`${this[Symbol.toStringTag]}:"${this.id}":${this.stats.nodeOrder.length} nodes:${this.stats.physicalTransientResourceBytes}B transient:${e}`}toJSON(){return this.toString()}constructor(e){this.device=e.device,this.id=e.id,this.buffers=e.buffers,this.textures=e.textures,this.externalTextures=e.externalTextures,this.compiledNodes=e.compiledNodes;for(let{node:t}of this.compiledNodes)for(let n of t.resources??[])if(rt(n)){let i=Te(n.buffer);i.transient||(this.activeImportedBufferHandles.add(i),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="copy-destination")&&this.writableImportedBufferHandles.add(i))}else if(tr(n)){let i=_e(n.texture);i.transient||(this.activeImportedTextureHandles.add(i),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="render-attachment"||n.usage==="copy-destination")&&this.writableImportedTextureHandles.add(i))}this.transientBuffers=e.transientBuffers,this.transientTextures=e.transientTextures,this.bufferTransientAllocations=e.bufferTransientAllocations,this.textureTransientAllocations=e.textureTransientAllocations,this.stats=e.stats,this.preflight=e.preflight,this.capabilities=Ha(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return $r(this.preflight,e,t)}createExecution(e,t={}){return new Gt({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(n,i,o,s)=>this.encodeNodeRange(n,i,o,s)})}encodeNodeRange(e,t,n,i){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Ir(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let o=nr(),s=this.resolveImportedBuffers(t.buffers??{});ja(t.frameTextures??{},t.externalTextures??{});let a=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[T,b]of a.frameIds)this.lastFrameIds.set(T,b);for(let[T,b]of u.frameIds)this.lastExternalTextureFrameIds.set(T,b);for(let T of u.textures.values())this.consumedExternalTextures.add(T);let c=a.textures,f=T=>{let b=Te(T),P=b.transient?this.transientBuffers.get(b):s.get(b);if(!P)throw new Error(`GPUCommandGraph buffer "${b.id}" is not bound`);return P},d=T=>{let b=_e(T),P=b.transient?this.transientTextures.get(b):c.get(b);if(!P)throw new Error(`GPUCommandGraph texture "${b.id}" is not bound`);return P},l=T=>{let b=d(T);if(T instanceof ve||Ii(T))return b.view;if(T.texture.frameScoped){let E=this.lastFrameIds.get(T.texture);for(let G=this.cachedTextureViews.length-1;G>=0;G--){let C=this.cachedTextureViews[G];C.logicalView===T&&C.frameId!==E&&(this.destroyFramebuffersUsingView(C.view),C.view.destroy(),this.cachedTextureViews.splice(G,1))}}let P=this.cachedTextureViews.find(E=>E.logicalView===T&&E.texture===b&&(!T.texture.frameScoped||E.frameId===this.lastFrameIds.get(T.texture)));if(P)return P.view;let B=b.createView({format:T.format,dimension:T.dimension,aspect:T.aspect,baseMipLevel:T.baseMipLevel,mipLevelCount:T.mipLevelCount,baseArrayLayer:T.baseArrayLayer,arrayLayerCount:T.arrayLayerCount});return this.cachedTextureViews.push({logicalView:T,texture:b,view:B,...T.texture.frameScoped?{frameId:this.lastFrameIds.get(T.texture)}:{}}),B},h=T=>{let b=u.textures.get(T);if(!b)throw new Error(`GPUCommandGraph external texture "${T.id}" is not bound`);return b},m={commandEncoder:e,parameters:t.parameters,getBuffer:f,getTexture:d,getTextureView:l,getExternalTexture:h},p=[],y,g=0,w=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,S=()=>{let T=y;y=void 0,T?.end()};try{for(let T=n;T<i;T++){let{node:b,executable:P}=this.compiledNodes[T],B=nr();if(b.condition?.source==="cpu"){let C=!1;try{C=b.condition.evaluate(t.parameters)}catch(I){let F=I instanceof Error?I.message:String(I);throw new Error(`GPUCommandGraph CPU condition "${b.condition.id}" failed for node "${b.id}": ${F}`)}if(!C){let I=nr();p.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[T].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:I,cpuEncodeTimeMilliseconds:I-B,hasGPUTimestamps:!1,condition:{id:b.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let E;switch(b.type){case"compute":{y||(y=e.beginComputePass({id:b.id}),g++);let C=y;E=Gi(C,e),E&&(w=!1),C.pushDebugGroup(b.id);try{let I=b.condition?.source==="gpu"?b.condition:void 0,F=I?za(C,f(I.buffer),I.byteOffset??0,b.id):void 0;P.encode({...m,computePass:F?.computePass??C}),F?.assertDispatched()}finally{C.popDebugGroup()}w||S();break}case"render":{S();let C=P,I=C.getRenderPassProps?.(m)??{id:b.id};if(b.attachments&&I.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply framebuffer with graph attachments`);if(b.attachments?.resolveTargets&&I.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply resolveTargets with graph attachments`);let F=b.attachments?this.getFramebuffer(b.id,b.attachments,l):void 0,M=b.attachments?.resolveTargets?.map(ee=>ee?l(ee):null),ce=e.beginRenderPass({...I,...F?{framebuffer:F}:{},...M?{resolveTargets:M}:{}});E=Gi(ce,e),ce.pushDebugGroup(b.id);try{C.encode({...m,renderPass:ce})}finally{ce.popDebugGroup(),ce.end()}break}case"copy":S(),P.encode(m);break}let G=nr();p.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[T].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:G,cpuEncodeTimeMilliseconds:G-B,hasGPUTimestamps:E!==void 0,...b.condition?{condition:{id:b.condition.id,source:b.condition.source,outcome:b.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:E})}}finally{S()}let v=nr();return new Dt(p,v-o,g,o,v,async(T,b)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let P=this.compiledNodes.findIndex(({node:F})=>F.id===T),B=this.compiledNodes[P]?.node.resources?.[b],E=this.preflight.nodes[P]?.resources?.[b];if(!B||!E)throw new Error("Resource is unavailable.");if("externalTexture"in B)throw new Error("External images cannot be read back.");let G="buffer"in B?Te(B.buffer):_e(B.texture);if("frameScoped"in G&&G.frameScoped)throw new Error("Frame textures expire after presentation.");let C="buffer"in B?f(B.buffer):d(B.texture),I=C instanceof oe.Buffer?this.transientBuffers:this.transientTextures;if(G.transient&&[...I].some(([F,M])=>F!==G&&M===C))throw new Error("Transient allocation is reused; logical contents are no longer available.");return $o(C,E)})}destroy(){if(!this.destroyed){for(let{executable:e}of this.compiledNodes)e.destroy?.();for(let e of this.cachedFramebuffers)e.framebuffer.destroy();for(let e of this.cachedTextureViews)e.view.destroy();for(let e of this.bufferTransientAllocations)e.buffer?.destroy();for(let e of this.textureTransientAllocations)e.texture?.destroy();this.destroyed=!0}}resolveImportedBuffers(e){let t=new Map,n=new Map;for(let[i,o]of this.buffers){if(o.transient)continue;let s=e[i]??o.defaultBuffer;if(!s)throw new Error(`GPUCommandGraph imported buffer "${i}" is required`);Ui(s,o,this.device);let a=or(s);if(this.activeImportedBufferHandles.has(o)){let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,f=n.get(c);if(f&&(this.writableImportedBufferHandles.has(f)||this.writableImportedBufferHandles.has(o)))throw new Error(`GPUCommandGraph imported buffers "${f.id}" and "${i}" resolve to the same physical buffer`);f||n.set(c,o)}t.set(o,a)}for(let i of Object.keys(e)){let o=this.buffers.get(i);if(!o||o.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${i}"`)}return t}resolveImportedTextures(e,t){let n=new Map,i=new Map;for(let[s,a]of this.textures){if(a.transient)continue;if(a.frameScoped){let c=t[s];if(!c)throw new Error(`GPUCommandGraph frame texture "${s}" is required`);let f=this.lastFrameIds.get(a);if(f!==void 0&&c.frameId<=f)throw new Error(`GPUCommandGraph frame texture "${s}" frameId ${c.frameId} is stale; expected greater than ${f}`);Zn(c.texture,a,this.device),n.set(a,Qn(c.texture)),i.set(a,c.frameId);continue}let u=e[s]??a.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${s}" is required`);Zn(u,a,this.device),n.set(a,Qn(u))}for(let s of Object.keys(e)){let a=this.textures.get(s);if(!a||a.transient||a.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${s}"`)}for(let s of Object.keys(t))if(!this.textures.get(s)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${s}"`);let o=new Map;for(let[s,a]of n){if(!this.activeImportedTextureHandles.has(s))continue;let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,f=o.get(c);if(f&&(this.writableImportedTextureHandles.has(f)||this.writableImportedTextureHandles.has(s)))throw new Error(`GPUCommandGraph imported textures "${f.id}" and "${s.id}" resolve to the same physical texture`);f||o.set(c,s)}return{textures:n,frameIds:i}}resolveExternalTextures(e){let t=new Map,n=new Map;for(let[i,o]of this.externalTextures){let s=e[i];if(!s)throw new Error(`GPUCommandGraph external texture "${i}" is required`);let a=this.lastExternalTextureFrameIds.get(o);if(a!==void 0&&s.frameId<=a)throw new Error(`GPUCommandGraph external texture "${i}" frameId ${s.frameId} is stale; expected greater than ${a}`);if(this.consumedExternalTextures.has(s.texture))throw new Error(`GPUCommandGraph external texture "${i}" requires a fresh binding for each frame`);Ka(s.texture,o,this.device),t.set(o,s.texture),n.set(o,s.frameId)}for(let i of Object.keys(e))if(!this.externalTextures.has(i))throw new Error(`GPUCommandGraph has no external texture named "${i}"`);return{textures:t,frameIds:n}}getFramebuffer(e,t,n){let i=t.colorAttachments.map(n),o=t.depthStencilAttachment?n(t.depthStencilAttachment):void 0,s=this.cachedFramebuffers.find(c=>c.nodeId===e&&c.depthStencilAttachment===o&&c.colorAttachments.length===i.length&&c.colorAttachments.every((f,d)=>f===i[d]));if(s)return s.framebuffer;let a=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:a.width,height:a.height,colorAttachments:i,depthStencilAttachment:o??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:i,depthStencilAttachment:o,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let n=this.cachedFramebuffers[t];(n.depthStencilAttachment===e||n.colorAttachments.some(i=>i===e))&&(n.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function or(r){return r instanceof xe?r.buffer:r}function Wa(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function rr(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function Qn(r){if(r instanceof Ze){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function ja(r,e){let t;for(let[n,i]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(i.frameId)||i.frameId<0)throw new Error(`GPUCommandGraph frame resource "${n}" requires a valid frameId`);if(t!==void 0&&i.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=i.frameId}}function Gi(r,e){let{timestampQuerySet:t,beginTimestampIndex:n,endTimestampIndex:i}=r.props;return t&&Number.isSafeInteger(n)&&Number.isSafeInteger(i)&&n>=0&&i>n?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:n,endIndex:i}:void 0}function Ha(r){return Object.freeze({timestampQueries:r.features.has("timestamp-query"),subgroups:r.features.has("subgroups"),subgroupId:r.wgslLanguageFeatures.has("subgroup_id"),subgroupMinSize:r.info.subgroupMinSize,subgroupMaxSize:r.info.subgroupMaxSize,softwareAdapter:r.info.gpu==="software"||r.info.gpuType==="cpu"||!!r.info.fallback,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension})}function Ir(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function nr(){return globalThis.performance?.now()??Date.now()}function Di(r,e){if(!r.id)throw new Error("GPUCommandGraph buffer id is required");if(!Number.isSafeInteger(r.byteLength)||r.byteLength<0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires a valid byteLength`);if(r.byteLength>e.limits.maxBufferSize)throw new Error(`GPUCommandGraph buffer "${r.id}" exceeds the device buffer limit`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires buffer usage flags`)}function qa(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,n]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`GPUCommandGraph external texture "${r.id}" ${t} must be a positive safe integer`);if(r.width>e.limits.maxTextureDimension2D||r.height>e.limits.maxTextureDimension2D)throw new Error(`GPUCommandGraph external texture "${r.id}" exceeds device dimension limits`)}function Xn(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",n=t==="cube"?6:r.depth??1,i=r.mipLevels??1,o=r.samples??1;for(let[c,f]of Object.entries({width:r.width,height:r.height,depth:n,mipLevels:i,samples:o}))if(!Number.isSafeInteger(f)||f<=0)throw new Error(`GPUCommandGraph texture "${r.id}" ${c} must be a positive safe integer`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph texture "${r.id}" requires texture usage flags`);if(!e.isTextureFormatSupported(r.format))throw new Error(`GPUCommandGraph texture "${r.id}" format ${r.format} is unsupported`);if(t==="1d"&&(r.height!==1||n!==1))throw new Error(`GPUCommandGraph 1d texture "${r.id}" requires height and depth 1`);if(t==="cube"&&r.width!==r.height)throw new Error(`GPUCommandGraph cube texture "${r.id}" must be square`);if(t==="cube-array"&&(r.width!==r.height||n%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(i>e.getMipLevelCount(r.width,r.height,t==="3d"?n:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let s=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,a=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>s||r.height>a||n>u)throw new Error(`GPUCommandGraph texture "${r.id}" exceeds device dimension limits`);return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:t,depth:n,mipLevels:i,samples:o}}function Ya(r,e){let t=e.dimension??r.dimension,n=e.aspect??"all",i=e.baseMipLevel??0,o=e.mipLevelCount??r.mipLevels-i,s=e.baseArrayLayer??0,a=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??a-s;for(let[l,h]of Object.entries({baseMipLevel:i,mipLevelCount:o,baseArrayLayer:s,arrayLayerCount:u}))if(!Number.isSafeInteger(h)||h<0)throw new Error(`Graph texture view ${l} must be a non-negative safe integer`);if(o===0||i+o>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||s+u>a||r.dimension==="3d"&&(s!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let c=Math.max(1,r.width>>i),f=r.dimension==="1d"?1:Math.max(1,r.height>>i),d=r.dimension==="3d"?Math.max(1,r.depth>>i):u;return{dimension:t,aspect:n,baseMipLevel:i,mipLevelCount:o,baseArrayLayer:s,arrayLayerCount:u,width:c,height:f,depth:d}}function Xa(r,e){for(let[i,o]of Object.entries(e))if(!Number.isSafeInteger(o)||o<0)throw new Error(`Graph data view ${i} must be a non-negative safe integer`);if(e.length>1&&e.byteStride===0)throw new Error("Graph data view byteStride must be positive for multiple rows");if(e.rowByteLength>e.byteStride&&e.length>1)throw new Error("Graph data view rowByteLength cannot exceed byteStride");let t=e.length===0?0:(e.length-1)*e.byteStride+e.rowByteLength,n=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n))throw new Error("Graph data view byte range exceeds safe integer precision");if(n>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function Ui(r,e,t){let n=or(r);if(n.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(n.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((n.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function Zn(r,e,t){let n=Qn(r);if(n.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[i,o,s]of[["format",e.format,n.format],["dimension",e.dimension,n.dimension],["width",e.width,n.width],["height",e.height,n.height],["depth",e.depth,n.depth],["mipLevels",e.mipLevels,n.mipLevels],["samples",e.samples,n.samples]])if(s!==o)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${i} (${s} !== ${o})`);if((n.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function Ka(r,e,t){if(r.device!==t)throw new Error(`GPUCommandGraph external texture "${e.id}" belongs to another device`);if(r.destroyed)throw new Error(`GPUCommandGraph external texture "${e.id}" has been destroyed`);if(r.width!==e.width||r.height!==e.height)throw new Error(`GPUCommandGraph external texture "${e.id}" has incompatible dimensions (${r.width}x${r.height} !== ${e.width}x${e.height})`)}function Qa(r,e){let t=eu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function Za(r,e){let t=tu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function Ja(r,e){if(r instanceof De&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function eu(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return oe.Buffer.STORAGE;case"uniform":return oe.Buffer.UNIFORM;case"copy-source":return oe.Buffer.COPY_SRC;case"copy-destination":return oe.Buffer.COPY_DST;case"indirect":return oe.Buffer.INDIRECT;case"vertex":return oe.Buffer.VERTEX;case"index":return oe.Buffer.INDEX}}function tu(r){switch(r){case"sampled":return oe.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return oe.Texture.STORAGE;case"render-attachment":return oe.Texture.RENDER;case"copy-source":return oe.Texture.COPY_SRC;case"copy-destination":return oe.Texture.COPY_DST}}function Ii(r){let e=r.texture;return r.dimension===e.dimension&&r.aspect==="all"&&r.baseMipLevel===0&&r.mipLevelCount===e.mipLevels&&r.baseArrayLayer===0&&r.arrayLayerCount===(e.dimension==="3d"?1:e.depth)}var ht=class extends Kn{constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");super(e,t)}};var wt=V(R(),1);var O=V(R(),1);var W={texture(r){return Object.freeze({...r,type:"texture",...r.extent?{extent:Object.freeze({...r.extent,..."scale"in r.extent&&r.extent.scale?{scale:Object.freeze([...r.extent.scale])}:{}})}:{}})},scalar(r){return Object.freeze({type:"scalar",format:r})},vector(r,e={}){return Object.freeze({type:"vector",format:r,...e,...e.chunkLengths?{chunkLengths:Object.freeze([...e.chunkLengths])}:{}})}},Oe=class{role;id;format;constructor(e,t,n){if(this.role=n,!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},K=class{id;format;length;external;role;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(e.length!==void 0&&(!Number.isSafeInteger(e.length)||e.length<0))throw new Error(`${e.id} vector length must be a non-negative safe integer`);if(this.id=e.id,this.format=e.format,this.length=e.length,this.external=e.external??!1,this.role=e.role,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.length!==void 0&&e.chunkLengths.reduce((t,n)=>t+n,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},ie=class{id;format;width;height;role;descriptor;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.role=e.role,this.descriptor=e.descriptor?W.texture(e.descriptor):void 0,this.id=e.id,this.format=e.format,this.width=e.width,this.height=e.height,this.usage=e.usage,this.dimension=e.dimension,this.depth=e.depth,this.mipLevels=e.mipLevels,this.samples=e.samples,this.external=e.external??!1}},Ue=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};function k(r){return typeof r=="string"?r:r.id}function Jn(r,e){let t=k(e),n=[...r.scalars,...r.vectors,...r.textures].find(i=>i.id===t);if(!n)throw new Error(`Undeclared operation value ${t}`);if(typeof e!="string"&&(e.constructor!==n.constructor||e.format!==n.format))throw new Error(`Incompatible operation reference ${t}`);return n}function Ot(r,e){for(let t of e.values){let n=Jn(r,t.value);if(n instanceof ie&&t.shape&&"like"in t.shape){if(!(Jn(r,t.shape.like)instanceof ie))throw new Error("Texture shape requires a texture source");continue}if(t.shape){if(!(n instanceof K)||t.access==="read")throw new Error("Operation shapes require writable vectors");if("like"in t.shape){if(!(Jn(r,t.shape.like)instanceof K))throw new Error("Operation shape source must be a vector");let i=k(t.shape.like);if(!e.values.some(o=>o.access!=="write"&&k(o.value)===i))throw new Error("Operation shape source must be a declared read")}else{let{length:i,chunkLengths:o}=t.shape;if(!Number.isSafeInteger(i)||i<0||o&&(o.some(s=>!Number.isSafeInteger(s)||s<0)||o.reduce((s,a)=>s+a,0)!==i))throw new Error("Invalid operation output shape")}}}}function ae(r){let e=r instanceof O.TextureView?r.texture:r,t=r instanceof O.TextureView?r.props:{},n=t.baseMipLevel??0,i=t.baseArrayLayer??0,o=t.dimension??e.dimension,s=t.mipLevelCount??e.mipLevels-n,a=o==="3d"?Math.max(1,e.depth>>n):t.arrayLayerCount??(o==="cube"?6:o==="2d"?1:e.depth-i);return(0,O.assert)((t.format??e.format)===e.format&&(t.aspect??"all")==="all"),(0,O.assert)(!r.destroyed&&!e.destroyed),(0,O.assert)(Number.isInteger(n)&&n>=0&&Number.isInteger(s)&&s>0&&n+s<=e.mipLevels),(0,O.assert)(Number.isInteger(i)&&i>=0&&Number.isInteger(a)&&a>0&&(o==="3d"?i===0:i+a<=e.depth)),{texture:e,format:e.format,dimension:o,width:Math.max(1,e.width>>n),height:Math.max(1,e.height>>n),depth:a,mipLevels:s,samples:e.samples,baseMipLevel:n,baseArrayLayer:i}}function $i(r,e={}){let t=ae(r),n=e.baseMipLevel??0,i=e.baseArrayLayer??0,o=e.dimension??t.dimension,s=e.mipLevelCount??t.mipLevels-n,a=e.arrayLayerCount??(o==="cube"?6:o==="2d"||o==="3d"?1:t.depth-i);return(0,O.assert)(n>=0&&n+s<=t.mipLevels&&i>=0&&i+a<=t.depth),{...e,dimension:o,baseMipLevel:t.baseMipLevel+n,mipLevelCount:s,baseArrayLayer:t.baseArrayLayer+i,arrayLayerCount:a}}var ru={sampled:O.Texture.SAMPLE,"storage-read":O.Texture.STORAGE,"storage-write":O.Texture.STORAGE,"storage-read-write":O.Texture.STORAGE,"render-attachment":O.Texture.RENDER,"copy-source":O.Texture.COPY_SRC,"copy-destination":O.Texture.COPY_DST},kr=class{values=new Map;owned=new Set;constructor(e,t,n,i,o){let s=new Map,a=new Set;for(let u of n)for(let c of u.values){let f=k(c.value);if(!t.some(l=>l.id===f))continue;(0,O.assert)(c.textureUsage);let d=c.textureUsage;(0,O.assert)(c.access==="read"&&["sampled","storage-read","copy-source"].includes(d)||c.access==="write"&&["storage-write","render-attachment","copy-destination"].includes(d)||c.access==="read-write"&&["storage-read-write","render-attachment"].includes(d)),s.set(f,(s.get(f)??0)|ru[d]),c.access!=="read"&&a.add(f)}try{let u=new Set(t);for(;u.size;){let c=!1;for(let f of u){let d=f.descriptor??{type:"texture",format:f.format,dimension:f.dimension,extent:f.width===void 0?void 0:{width:f.width,height:f.height,depth:f.depth},mipLevels:f.mipLevels,samples:f.samples},l=d.extent,h=l&&"like"in l?this.values.get(l.like):void 0;if(l&&"like"in l&&!h)continue;let m=h?ae(h):void 0,p=l&&"like"in l?l.scale??[1,1]:[1,1];(0,O.assert)(p.every(E=>Number.isFinite(E)&&E>0));let y=m?Math.max(1,Math.round(m.width*p[0])):l&&"width"in l?l.width:void 0,g=m?Math.max(1,Math.round(m.height*p[1])):l&&"height"in l?l.height:void 0,w=d.dimension??m?.dimension??"2d",S=w==="cube"?6:m?.depth??(l&&"depth"in l?l.depth:void 0),v=d.mipLevels??m?.mipLevels??1,T=d.samples??m?.samples??1,b=(s.get(f.id)??0)|f.usage;(0,O.assert)(T===1||!(b&(O.Texture.COPY_SRC|O.Texture.COPY_DST)));let P=o[f.id]??i[f.id];if(P===void 0){(0,O.assert)(f.role!=="input"&&!f.external&&y!==void 0&&g!==void 0&&b!==0),(0,O.assert)(Number.isSafeInteger(y)&&y>0&&Number.isSafeInteger(g)&&g>0);let E=e.createTexture({id:f.id,format:d.format,dimension:w,width:y,height:g,depth:S??1,mipLevels:v,samples:T,usage:b|(T===1?O.Texture.COPY_SRC:0)|O.Texture.SAMPLE});this.owned.add(E),P=E}(0,O.assert)(P instanceof O.Texture||P instanceof O.TextureView);let B=ae(P);(0,O.assert)(B.samples===1||!(b&(O.Texture.COPY_SRC|O.Texture.COPY_DST))),(0,O.assert)(B.texture.device===e&&B.format===d.format&&B.dimension===w&&(y===void 0||B.width===y)&&(g===void 0||B.height===g)&&(S===void 0||B.depth===S)&&(d.mipLevels===void 0&&f.role==="input"||B.mipLevels===v)&&(d.samples===void 0&&f.role==="input"||B.samples===T)&&(B.texture.props.usage&b)===b),this.values.set(f.id,P),u.delete(f),c=!0}(0,O.assert)(c)}for(let c of a){let f=ae(this.values.get(c)).texture;for(let[d,l]of this.values)(0,O.assert)(c===d||ae(l).texture!==f)}}catch(u){throw this.destroy(),u}}finish(e){for(let t of e){let n=this.values.get(t);n instanceof O.Texture&&this.owned.delete(n)}this.destroy()}destroy(){for(let e of this.owned)e.destroy();this.owned.clear()}};var ki=V(R(),1);function Ai(r,e,t){let n=ae(e),i=ae(t);eo(e,t);for(let o=0;o<n.mipLevels;o++)r.copyTextureToTexture({sourceTexture:n.texture,destinationTexture:i.texture,mipLevel:n.baseMipLevel+o,destinationMipLevel:i.baseMipLevel+o,origin:[0,0,n.baseArrayLayer],destinationOrigin:[0,0,i.baseArrayLayer],width:Math.max(1,n.width>>o),height:Math.max(1,n.height>>o),depthOrArrayLayers:n.dimension==="3d"?Math.max(1,n.depth>>o):n.depth})}function eo(r,e){let t=ae(r),n=ae(e);(0,ki.assert)(t.texture!==n.texture&&t.samples===1&&n.samples===1&&t.format===n.format&&t.width===n.width&&t.height===n.height&&t.depth===n.depth&&t.mipLevels===n.mipLevels&&t.dimension===n.dimension)}var ir=V(R(),1);function _i(r,e){let t=e.resolveVector(r.output),n=r.getData();for(let[i,o]of t.data.entries()){if(!o.length)continue;let s=n[i];e.graph.addCopyPass({id:`${r.id}-${i}`,resources:[{buffer:o,usage:"copy-destination"}],compile:({device:a})=>{let u=a.createBuffer({data:s,usage:ir.Buffer.COPY_SRC});return{encode:({commandEncoder:c,getBuffer:f})=>{let d=o.byteStride===o.rowByteLength;for(let l=0;l<o.length;l+=d?o.length:1)c.copyBufferToBuffer({sourceBuffer:u,sourceOffset:l*o.rowByteLength,destinationBuffer:f(o),destinationOffset:o.byteOffset+l*o.byteStride,size:d?s.byteLength:o.rowByteLength})},destroy:()=>u.destroy()}}})}}function Fi(r,e){let t=e.resolveVector(r.input),n=e.resolveVector(r.output);(0,ir.assert)(t.format===n.format&&t.data.length===n.data.length);for(let[i,o]of t.data.entries()){let s=n.data[i];(0,ir.assert)(o.length===s.length),o.length&&e.graph.addCopyPass({id:`${r.id}-${i}`,resources:[{buffer:o,usage:"copy-source"},{buffer:s,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:a,getBuffer:u})=>{let c=o.byteStride===o.rowByteLength&&s.byteStride===s.rowByteLength;for(let f=0;f<o.length;f+=c?o.length:1)a.copyBufferToBuffer({sourceBuffer:u(o),sourceOffset:o.byteOffset+f*o.byteStride,destinationBuffer:u(s),destinationOffset:s.byteOffset+f*s.byteStride,size:o.rowByteLength*(c?o.length:1)})}})})}}function Ri(r,e){let t=e.resolveTextureView(r.input),n=e.resolveTextureView(r.output);e.graph.addCopyPass({id:r.id,resources:[{texture:t,usage:"copy-source"},{texture:n,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:i,getTextureView:o})=>Ai(i,o(t),o(n))})})}var to=V(R(),1);var Me=class{type="vector-upload";id;output;format;chunks;chunkLengths;constructor(e){this.id=e.id??`${e.output}-upload`,this.output=e.output,this.format=e.format;let t=U(e.format),n=Array.isArray(e.data)?e.data:[e.data],i=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array;(0,to.assert)(n.every(o=>o instanceof i&&o.byteLength%t.byteLength===0)),this.chunks=n.map(o=>new Uint8Array(o.buffer,o.byteOffset,o.byteLength).slice()),this.chunkLengths=Object.freeze(this.chunks.map(o=>o.byteLength/t.byteLength))}getData(){return this.chunks.map(e=>e.slice())}get contract(){let e={length:this.chunkLengths.reduce((t,n)=>t+n,0),chunkLengths:this.chunkLengths};return{outputs:{[this.output]:W.vector(this.format,e)},values:[{value:this.output,access:"write",shape:e}]}}},Ve=class{type="vector-copy";id;input;output;constructor(e){this.id=e.id??`${e.output}-copy`,this.input=e.input,this.output=e.output}get contract(){return{outputs:({getValue:e})=>{let t=e(this.input);return t.type==="texture"?{[this.output]:W.texture({...t,extent:{like:this.input}})}:((0,to.assert)(t.type==="vector"),{[this.output]:W.vector(t.format,{length:t.length,chunkLengths:t.chunkLengths})})},values:[{value:this.input,access:"read",textureUsage:"copy-source"},{value:this.output,access:"write",shape:{like:this.input},textureUsage:"copy-destination"}]}}};function z(r,e){let[t,n,i]=e;for(let[o,s]of[["x",t],["y",n],["z",i]])if(!Number.isSafeInteger(s)||s<0)throw new Error(`compute dispatch ${o} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,n,i])}}function Ar(r){return r.dispatchWorkgroups}var Ne=V(R(),1),_=class r{static async createAsync(e,t){let n=!Ne.PipelineFactory.getAsyncCompilation(e),i=n?Ne.PipelineFactory.beginAsyncCompilation(e):Ne.PipelineFactory.getAsyncCompilation(e),o;try{o=new r(e,t)}finally{n&&Ne.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await o._pipelineInitialization,o}catch(s){throw o.destroy(),s}}device;id;source;pipelineFactory;shaderFactory;shader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Kernel is only supported in WebGPU");let{source:n,pipelineFactory:i,shaderFactory:o,debugShaders:s,...a}=t;this.device=e,this.id=t.id??"kernel",this.source=n,this.pipelineFactory=i??Ne.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=o??Ne.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:s});let u={...a,shader:this.shader},c=Ne.PipelineFactory.getAsyncCompilation(e);if(c){let f=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=f,c.push(f.then(d=>(this.pipeline=d,d)))}else this.pipeline=this.pipelineFactory.createComputePipeline(u)}dispatch(e,t){this._setPipeline(e,t.bindings),e.dispatch(t.x,t.y,t.z)}dispatchIndirect(e,t){this._setPipeline(e,t.bindings),e.dispatchIndirect(t.indirectBuffer,t.indirectOffset??0)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._destroyed=!0)}_setPipeline(e,t={}){e.setPipeline(this.pipeline),e.setBindings(t)}};function ze(r,e,t,n){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);Mi(r,t);let i=Math.floor(n);if(!Number.isSafeInteger(i)||i<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let o=Math.max(1,Math.ceil(e/t)),s=Math.min(o,i),a=Math.min(Math.ceil(o/s),i),u=Math.ceil(o/s/a);if(u>i)throw new Error(`${r} requires ${o} workgroups, exceeding the 3D dispatch limit of ${i} per dimension`);return{x:s,y:a,z:u}}function he(r,e){Mi("GPU dispatch",e);let t=Math.floor(4294967295/e)+1;return`let workgroupIndex = (workgroupId.z * ${r.y}u + workgroupId.y) * ${r.x}u + workgroupId.x;
7
+ "use strict";var __exports__=(()=>{var Gs=Object.create;var Tr=Object.defineProperty;var Ds=Object.getOwnPropertyDescriptor;var Is=Object.getOwnPropertyNames;var Us=Object.getPrototypeOf,$s=Object.prototype.hasOwnProperty;var ks=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},As=(r,e)=>{for(var t in e)Tr(r,t,{get:e[t],enumerable:!0})},wr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Is(e))!$s.call(r,o)&&o!==t&&Tr(r,o,{get:()=>e[o],enumerable:!(n=Ds(e,o))||n.enumerable});return r},vr=(r,e,t)=>(wr(r,e,"default"),t&&wr(t,e,"default")),R=(r,e,t)=>(t=r!=null?Gs(Us(r)):{},wr(e||!r||!r.__esModule?Tr(t,"default",{value:r,enumerable:!0}):t,r)),_s=r=>wr(Tr({},"__esModule",{value:!0}),r);var A=ks((oc,Fo)=>{Fo.exports=globalThis.luma});var xr={};As(xr,{CompiledGPUCommandGraph:()=>ht,CompiledGPUGraph:()=>jt,DynamicBuffer:()=>we,DynamicTexture:()=>Je,GPUCPUOperation:()=>be,GPUCommandGraph:()=>mt,GPUCommandGraphAutotuner:()=>dn,GPUCommandGraphEncoding:()=>Ut,GPUCommandGraphExecution:()=>It,GPUCommandGraphExecutionBudgetController:()=>fn,GPUCommandGraphInspector:()=>hn,GPUCompactionOperation:()=>pn,GPUCopyOperation:()=>Ne,GPUExpressionOperation:()=>$e,GPUGraph:()=>Ce,GPUGraphCompiler:()=>wt,GPUGraphScalar:()=>Ie,GPUGraphTexture:()=>ae,GPUGraphTextureView:()=>Ue,GPUGraphVector:()=>K,GPUShaderPassOperation:()=>at,GPUUploadOperation:()=>Ve,GraphBufferHandle:()=>Re,GraphDataView:()=>Ge,GraphExternalTextureHandle:()=>ot,GraphTextureHandle:()=>Se,GraphTextureView:()=>De,GraphVectorView:()=>G,Kernel:()=>F,PreparedGPUGraphExecution:()=>gr,RenderKernel:()=>zt,composite:()=>Bo,getGPUCommandGraphAdapterIdentity:()=>Es,getGPUCommandGraphExecutionPlan:()=>Rr,getPlatformInfo:()=>Bs,gpuGraph:()=>N,inspectGPUGraphCompilation:()=>Oo,validateGPUGraph:()=>lr});vr(xr,R(A(),1));var ct=R(A(),1);async function Ro(r,e){if(r.destroyed)throw new Error("Resource has been destroyed.");if(r instanceof ct.Buffer){if(!(r.usage&ct.Buffer.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");let c=e.byteOffset??0,d=Math.min(256,e.byteLength??r.byteLength-c);if(c<0||d<0||c+d>r.byteLength)throw new Error("Preview range is outside the buffer.");return{data:d?await r.readAsync(c,d):new Uint8Array,format:e.format}}let t=r.device.getTextureFormatInfo(r.format);if(t.packed)throw new Error("Packed texture previews are not supported.");if(r.device.type!=="webgpu")throw new Error("Texture previews require WebGPU.");if(!((r.props.usage??0)&ct.Texture.COPY_SRC))throw new Error("Preview requires COPY_SRC usage.");if(r.samples!==1||t.compressed||r.format.startsWith("depth")||r.format.startsWith("stencil"))throw new Error("Preview requires a single-sample, uncompressed color texture.");let n=e.baseMipLevel??0,o=Math.min(32,e.width??Math.max(1,r.width>>n)),i=Math.min(32,e.height??Math.max(1,r.height>>n)),s=r.computeMemoryLayout({width:o,height:i,depthOrArrayLayers:1}),a=r.device.createBuffer({byteLength:s.byteLength,usage:ct.Buffer.MAP_READ|ct.Buffer.COPY_DST}),u=r.device.createCommandEncoder();try{u.copyTextureToBuffer({sourceTexture:r,destinationBuffer:a,mipLevel:n,origin:[0,0,e.baseArrayLayer??0],width:o,height:i,depthOrArrayLayers:1,bytesPerRow:s.bytesPerRow}),r.device.submit(u.finish());let c=await a.readAsync(),d=o*t.bytesPerPixel,f=new Uint8Array(d*i);for(let l=0;l<i;l++)f.set(c.subarray(l*s.bytesPerRow,l*s.bytesPerRow+d),l*d);return{data:f,width:o,height:i,format:r.format}}finally{a.destroy(),u.destroy()}}var se=R(A(),1);var Wt=globalThis,Fs=globalThis.document||{},Sr=globalThis.process||{},Rs=globalThis.console,Ms=globalThis.navigator||{};function Er(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 Ye(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||Er()}var gn="5.0.0";function St(r,e){if(!r)throw new Error(e||"Assertion failed")}function Pr(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 St(Number.isFinite(e)&&e>=0),e}function yn(r){let{logLevel:e,message:t}=r;r.logLevel=Pr(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 o=typeof r.message;return St(o==="string"||o==="object"),Object.assign(r,{args:n},r.opts)}var Xe=()=>{},dt=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,o,i={}){let s=yn({logLevel:t,message:n,args:this._buildArgs(t,n,o),opts:i});return this._createLogFunction(e,s,i)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return Xe;let o=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&o!==void 0){if(this._onceCache.has(o))return Xe;this._onceCache.add(o)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=Pr(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function Ns(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var Ht=class{constructor(e,t,n="sessionStorage"){this.storage=Ns(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 Mo(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 bn(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var qt;(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"})(qt||(qt={}));var zs=10;function Vo(r){return typeof r!="string"?r:(r=r.toUpperCase(),qt[r]||qt.WHITE)}function xn(r,e,t){return!Ye&&typeof r=="string"&&(e&&(r=`\x1B[${Vo(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${Vo(t)+zs}m${r}\x1B[49m`)),r}function wn(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),o=r;for(let i of n){let s=o[i];typeof s=="function"&&(e.find(a=>i===a)||(o[i]=s.bind(r)))}}var Cr=class{getHighResolutionTimer(){let e;if(Ye()&&Wt.performance)e=Wt?.performance?.now?.();else if("hrtime"in Sr){let t=Sr?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=Wt?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},le=new Cr;globalThis.Probe=Cr;globalThis.probe=le;var Et={debug:Ye()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},Tn={enabled:!0,level:0},ke=class extends dt{constructor({id:e}={id:""}){super({level:0}),this.VERSION=gn,this._startTs=le.getHighResolutionTimer(),this._deltaTs=le.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new Ht(`__probe-${this.id}__`,{[this.id]:Tn}),this.timeStamp(`${this.id} started`),wn(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((le.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((le.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:Et.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:Et.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 o=le.getMemoryUsageMB();if(o!==null){let i=`${o}MB `;typeof t=="function"?t=()=>`${i}${t()}`:typeof t=="string"&&(t=`${i}${t}`)}return this._log("log",e,t,n,{method:Et.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:Et.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:Et.debug||Et.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||Xe,tag:Ws(t)}):Xe}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||Xe})}group(e,t,n={collapsed:!1}){let o=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:o})}groupCollapsed(e,t,n={}){return this.group(e,t,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||Xe})}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;St(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=le.getHighResolutionTimer();let o=js(this.id,t.message,t);return n.bind(console,o,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(Tn),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...Tn};this._storage.setConfiguration({[this.id]:{...t,...e}})}};ke.VERSION=gn;function js(r,e,t){if(typeof e=="string"){let n=t.time?bn(Mo(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=xn(e,t.color,t.background)}return e}function Ws(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=le);var id=new ke({id:"@probe.gl/log"});var xe=new ke({id:"luma.gl"});var vn={};function Pt(r="id"){vn[r]=vn[r]||1;let e=vn[r]++;return`${r}-${e}`}var Hs="cpu-hotspot-profiler",No="GPU Resource Counts",zo="Resource Counts",jo="GPU Time and Memory",qs=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Ys=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],Xs=qs.flatMap(r=>[`${r} Created`,`${r} Active`]),Ks=Ys.flatMap(r=>[`${r} Created`,`${r} Active`]),Wo=new WeakMap,Ho=new WeakMap,he=class{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;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;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(!e)throw new Error("no device");this._device=e,this.props=Qs(t,n);let o=this.props.id!=="undefined"?this.props.id:Pt(this[Symbol.toStringTag]);this.props.id=o,this.id=o,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=Yt(this._device),t=e?Ke():0,n=[this._device.statsManager.getStats(No),this._device.statsManager.getStats(zo)],o=Yo(this._device);for(let s of n)qo(s,o);let i=this.getStatsName();for(let s of n)s.get("Resources Active").decrementCount(),s.get(`${i}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(Ke()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=Yt(this._device),o=n?Ke():0,i=this._device.statsManager.getStats(jo);this.allocatedBytes>0&&this.allocatedBytesName&&(i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),i.get("GPU Memory").addCount(e),i.get(`${t} Memory`).addCount(e),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(Ke()-o)),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=Yt(this._device),n=t?Ke():0,o=this._device.statsManager.getStats(jo);o.get("GPU Memory").subtractCount(this.allocatedBytes),o.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(Ke()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=Yt(this._device),n=t?Ke():0,o=[this._device.statsManager.getStats(No),this._device.statsManager.getStats(zo)],i=Yo(this._device);for(let s of o)qo(s,i);for(let s of o)s.get("Resources Created").incrementCount(),s.get("Resources Active").incrementCount(),s.get(`${e}s Created`).incrementCount(),s.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(Ke()-n)),Zs(this._device,e)}getStatsName(){return Js(this)}};function Qs(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function qo(r,e){let t=r.stats,n=!1;for(let u of e)t[u]||(r.get(u),n=!0);let o=Object.keys(t).length,i=Wo.get(r);if(!n&&i?.orderedStatNames===e&&i.statCount===o)return;let s={},a=Ho.get(e);a||(a=new Set(e),Ho.set(e,a));for(let u of e)t[u]&&(s[u]=t[u]);for(let[u,c]of Object.entries(t))a.has(u)||(s[u]=c);for(let u of Object.keys(t))delete t[u];Object.assign(t,s),Wo.set(r,{orderedStatNames:e,statCount:o})}function Yo(r){return r.type==="webgl"?Ks:Xs}function Yt(r){let e=r.userData[Hs];return e?.enabled?e:null}function Ke(){return globalThis.performance?.now?.()??Date.now()}function Zs(r,e){let t=Yt(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 Js(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===he.prototype)return ea(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function ea(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 Le=class r extends he{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 o=null,i;ArrayBuffer.isView(e)?(o=e,i=e.buffer):i=e;let s=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(i===null)this.debugData=new ArrayBuffer(s);else{let a=Math.min(o?.byteOffset||0,i.byteLength),u=Math.max(0,i.byteLength-a),c=Math.min(s,u);this.debugData=new Uint8Array(i,a,c).slice().buffer}}static defaultProps={...he.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var Sn=globalThis.Float16Array;function Xo(){return Sn??Uint16Array}function Ko(r){return!!(Sn&&r===Sn)}function Lr(r,e){switch(e){case 1:return r;case 2:return r+r%2;default:return r+(4-r%4)%4}}var Qo=new Map;function Zo(r){let e=Qo.get(r);if(e)return e;let t=Object.freeze(ta(r));return Object.hasOwn(Br,r)&&Qo.set(r,t),t}function ta(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),o=Br[r],[i,s,a]=o||["uint8 ","i32",1];return{signedType:i,primitiveType:s,byteLength:a,normalized:e,integer:t,signed:n}}function Jo(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 ra(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if(Ko(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(Br).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function ei(r){return ra(r)}function na(r){if(r==="float16")return Xo();let e=Br[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function ti(r){return na(r)}var Br={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 En=class{getDataTypeInfo(e){return Zo(e)}getNormalizedDataType(e){return Jo(e)}alignTo(e,t){return Lr(e,t)}getDataType(e){return ei(e)}getTypedArrayConstructor(e){return ti(e)}},ri=new En;var re="texture-compression-bc",_="texture-compression-astc",Be="texture-compression-etc2",ni="texture-compression-etc1-webgl",Or="texture-compression-pvrtc-webgl",Pn="texture-compression-atc-webgl",Gr="float32-renderable-webgl",Cn="float16-renderable-webgl",oa="rgb9e5ufloat-renderable-webgl",Ln="snorm8-renderable-webgl",Qe="norm16-webgl",Bn="norm16-renderable-webgl",On="snorm16-renderable-webgl",Dr="float32-filterable",oi="float16-filterable-webgl",Xt=1,Kt=2,In=4,Un=8,Lt=16,Ur=5,si=10,X=Xt|Kt,Ir=Xt|In,Ae=Xt|Kt|In|Un,Oe=Xt|Kt|Lt,ia=Xt|In|Lt,Dn=Ae|Lt,ii=(Kt|Un|Lt)<<Ur,sa=(Kt|Un)<<Ur,ie=Lt<<Ur,Ct=Dn<<Ur,aa=Ae<<si,Gn=Lt<<si;function $r(r){let e=da[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var ua={r8unorm:{webgpu:Ae|ie},rg8unorm:{webgpu:Ae|ie},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:Dn},"rgba8unorm-srgb":{webgpu:Ae},r8snorm:{render:Ln,webgpu:Ir|ii},rg8snorm:{render:Ln,webgpu:Ir|ii},"rgb8snorm-webgl":{},rgba8snorm:{render:Ln,webgpu:ia|sa},r8uint:{webgpu:X|ie},rg8uint:{webgpu:X|ie},rgba8uint:{webgpu:Oe},r8sint:{webgpu:X|ie},rg8sint:{webgpu:X|ie},rgba8sint:{webgpu:Oe},bgra8unorm:{webgpu:Ae},"bgra8unorm-srgb":{webgpu:aa},r16unorm:{f:Qe,render:Bn,webgpu:Ct},rg16unorm:{f:Qe,render:Bn,webgpu:Ct},"rgb16unorm-webgl":{f:Qe,render:!1},rgba16unorm:{f:Qe,render:Bn,webgpu:Ct},r16snorm:{f:Qe,render:On,webgpu:Ct},rg16snorm:{f:Qe,render:On,webgpu:Ct},"rgb16snorm-webgl":{f:Qe,render:!1},rgba16snorm:{f:Qe,render:On,webgpu:Ct},r16uint:{webgpu:X|ie},rg16uint:{webgpu:X|ie},rgba16uint:{webgpu:Oe},r16sint:{webgpu:X|ie},rg16sint:{webgpu:X|ie},rgba16sint:{webgpu:Oe},r16float:{render:Cn,filter:"float16-filterable-webgl",webgpu:Ae|ie},rg16float:{render:Cn,filter:oi,webgpu:Ae|ie},rgba16float:{render:Cn,filter:oi,webgpu:Dn},r32uint:{webgpu:Oe},rg32uint:{webgpu:X|Gn},rgba32uint:{webgpu:Oe},r32sint:{webgpu:Oe},rg32sint:{webgpu:X|Gn},rgba32sint:{webgpu:Oe},r32float:{render:Gr,filter:Dr,webgpu:Oe},rg32float:{render:!1,filter:Dr,webgpu:X|Gn},"rgb32float-webgl":{render:Gr,filter:Dr},rgba32float:{render:Gr,filter:Dr,webgpu:Oe},"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:oa,webgpu:Ir},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Gr,webgpu:Ir|ie},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:Ae|ie},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:X|ie},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:X},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:X},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:X},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:X},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:X},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:X}},ca={"bc1-rgb-unorm-webgl":{f:re},"bc1-rgb-unorm-srgb-webgl":{f:re},"bc1-rgba-unorm":{f:re},"bc1-rgba-unorm-srgb":{f:re},"bc2-rgba-unorm":{f:re},"bc2-rgba-unorm-srgb":{f:re},"bc3-rgba-unorm":{f:re},"bc3-rgba-unorm-srgb":{f:re},"bc4-r-unorm":{f:re},"bc4-r-snorm":{f:re},"bc5-rg-unorm":{f:re},"bc5-rg-snorm":{f:re},"bc6h-rgb-ufloat":{f:re},"bc6h-rgb-float":{f:re},"bc7-rgba-unorm":{f:re},"bc7-rgba-unorm-srgb":{f:re},"etc2-rgb8unorm":{f:Be},"etc2-rgb8unorm-srgb":{f:Be},"etc2-rgb8a1unorm":{f:Be},"etc2-rgb8a1unorm-srgb":{f:Be},"etc2-rgba8unorm":{f:Be},"etc2-rgba8unorm-srgb":{f:Be},"eac-r11unorm":{f:Be},"eac-r11snorm":{f:Be},"eac-rg11unorm":{f:Be},"eac-rg11snorm":{f:Be},"astc-4x4-unorm":{f:_},"astc-4x4-unorm-srgb":{f:_},"astc-5x4-unorm":{f:_},"astc-5x4-unorm-srgb":{f:_},"astc-5x5-unorm":{f:_},"astc-5x5-unorm-srgb":{f:_},"astc-6x5-unorm":{f:_},"astc-6x5-unorm-srgb":{f:_},"astc-6x6-unorm":{f:_},"astc-6x6-unorm-srgb":{f:_},"astc-8x5-unorm":{f:_},"astc-8x5-unorm-srgb":{f:_},"astc-8x6-unorm":{f:_},"astc-8x6-unorm-srgb":{f:_},"astc-8x8-unorm":{f:_},"astc-8x8-unorm-srgb":{f:_},"astc-10x5-unorm":{f:_},"astc-10x5-unorm-srgb":{f:_},"astc-10x6-unorm":{f:_},"astc-10x6-unorm-srgb":{f:_},"astc-10x8-unorm":{f:_},"astc-10x8-unorm-srgb":{f:_},"astc-10x10-unorm":{f:_},"astc-10x10-unorm-srgb":{f:_},"astc-12x10-unorm":{f:_},"astc-12x10-unorm-srgb":{f:_},"astc-12x12-unorm":{f:_},"astc-12x12-unorm-srgb":{f:_},"pvrtc-rgb4unorm-webgl":{f:Or},"pvrtc-rgba4unorm-webgl":{f:Or},"pvrtc-rgb2unorm-webgl":{f:Or},"pvrtc-rgba2unorm-webgl":{f:Or},"etc1-rgb-unorm-webgl":{f:ni},"etc1-rbg-unorm-webgl":{f:ni},"atc-rgb-unorm-webgl":{f:Pn},"atc-rgba-unorm-webgl":{f:Pn},"atc-rgbai-unorm-webgl":{f:Pn}},da={...ua,...ca};var fa=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,la=["rgb","rgba","bgra"],ha=["depth","stencil"],ma=5,pa=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],$n=class{isColor(e){return la.some(t=>e.startsWith(t))}isDepthStencil(e){return ha.some(t=>e.startsWith(t))}isCompressed(e){return pa.some(t=>e.startsWith(t))}getInfo(e){return ui(e)}getCapabilities(e){return ya(e)}getWebGPUCapabilities(e){let t=$r(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?ma:0}computeMemoryLayout(e,t){return ga(e,t)}},Bt=new $n;function ga({format:r,width:e,height:t,depth:n,byteAlignment:o},i={}){let s=Bt.getInfo(r),{bytesPerPixel:a,blockHeight:u=1,compressed:c=!1}=s,d=kn(s,e,o),f=c?Math.ceil(t/u):t;return i.bytesPerPixel=a,i.bytesPerRow=d,i.rowsPerImage=f,i.depthOrArrayLayers=n,i.bytesPerImage=d*f,i.byteLength=i.bytesPerImage*n,i}function kn(r,e,t){let{bytesPerPixel:n,bytesPerBlock:o=n,blockWidth:i=1,compressed:s=!1}=r,a=s?Math.ceil(e/i):e;return Math.ceil(a*o/t)*t}function ya(r){let e=$r(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=ui(r),o=r.startsWith("depth")||r.startsWith("stencil"),i=n?.signed,s=n?.integer,a=n?.webgl,u=!!n?.compressed;return t.render&&=!o&&!u,t.filter&&=!o&&!i&&!s&&!a,t}var ai=new Map;function ui(r){let e=ai.get(r);if(!e){let t=ba(r);t.bitsPerChannel=Object.freeze([...t.bitsPerChannel]),e=Object.freeze(t),ai.set(r,e)}return e}function ba(r){let e=xa(r);if(Bt.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=Ta(r);let n=wa(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:fa.exec(r);if(t){let[,n,o,i,s,a]=t,u=`${i}${o}`,c=ri.getDataTypeInfo(u),d=c.byteLength*8,f=n?.length??1,l=[d,f>=2?d:0,f>=3?d:0,f>=4?d:0];e={format:r,attachment:e.attachment,dataType:c.signedType,components:f,channels:n,integer:c.integer,signed:c.signed,normalized:c.normalized,bitsPerChannel:l,bytesPerPixel:c.byteLength*f,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),s==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function xa(r){let e={...$r(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 wa(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,n,o]=t;return{blockWidth:Number(n),blockHeight:Number(o)}}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 Ta(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 Qt(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 kr(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 Ze=class r extends he{static defaultProps={...he.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}};var ci=[],va=Object.freeze({}),Sa={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},ne=class r extends he{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=Sa[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 o=e.getExternalImageSize(t.data);this.width=o?.width||1,this.height=o?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&xe.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){this.sampler=e instanceof Ze?e:this.device.createSampler(e)}copyImageData(e){let{data:t,depth:n,...o}=e;this.writeData(t,{...o,depthOrArrayLayers:o.depthOrArrayLayers??n})}computeMemoryLayout(e=va,t){let n=ci.pop()||{readOptions:{},layoutOptions:{}};try{let o=this._normalizeTextureReadOptions(e,n.readOptions),i=n.layoutOptions;return i.format=this.format,i.width=o.width,i.height=o.height,i.depth=o.depthOrArrayLayers,i.byteAlignment=this.byteAlignment,Bt.computeMemoryLayout(i,t)}finally{ci.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:o,height:i}=n;return typeof o=="number"&&(n.width=Math.max(1,Math.ceil(o))),typeof i=="number"&&(n.height=Math.max(1,Math.ceil(i))),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:o,depthOrArrayLayers:i}=e;if(this._normalizeTextureWriteOptions(e,t),i===void 0&&o!==void 0){let s=this.dimension==="3d"?Math.max(1,this.depth>>t.mipLevel):this.depth;t.depthOrArrayLayers=Math.min(o,s-t.z)}return t.data=n,t.depth=t.depthOrArrayLayers,t}_normalizeCopyExternalImageOptions(e,t={}){let{width:n,height:o}=e,i=this.device.getExternalImageSize(e.image),s=r._normalizeOptions(e,r.defaultCopyExternalImageOptions,t),a=Math.max(1,this.width>>s.mipLevel),u=this.baseDimension==="1d"?1:Math.max(1,this.height>>s.mipLevel),c=this.dimension==="3d"?Math.max(1,this.depth>>s.mipLevel):this.depth;return s.width=Math.min(n??i.width,a-s.x),s.height=Math.min(o??i.height,u-s.y),s.depth=Math.min(s.depth,c-s.z),s}_normalizeCopyElementImageOptions(e,t={}){let n=r._normalizeOptions(e,r.defaultCopyElementImageOptions,t),o=Math.max(1,this.width>>n.mipLevel),i=this.baseDimension==="1d"?1:Math.max(1,this.height>>n.mipLevel),s=this.dimension==="3d"?Math.max(1,this.depth>>n.mipLevel):this.depth;return n.width=Math.min(n.width??o,o-n.x),n.height=Math.min(n.height??i,i-n.y),n.depth=Math.min(n.depth,s-n.z),n}_normalizeTextureReadOptions(e,t={}){let{depthOrArrayLayers:n}=e,o=r._normalizeOptions(e,r.defaultTextureReadOptions,t),i=Math.max(1,this.width>>o.mipLevel),s=this.baseDimension==="1d"?1:Math.max(1,this.height>>o.mipLevel),a=this.dimension==="3d"?Math.max(1,this.depth>>o.mipLevel):this.depth;return o.width=Math.min(o.width??i,i-o.x),o.height=Math.min(o.height??s,s-o.y),o.depthOrArrayLayers=Math.min(n??a,a-o.z),o}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=Bt.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:o,rowsPerImage:i}=e;this._normalizeTextureReadOptions(e,t);let s=t;s.byteOffset=n;let a=this.device.getTextureFormatInfo(this.format),u=a.bytesPerPixel*s.width;if(s.bytesPerRow=o??kn(a,s.width,this.byteAlignment),s.rowsPerImage=i??s.height,s.bytesPerRow<u)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be at least ${u} for ${this.format}`);if(s.rowsPerImage<s.height)throw new Error(`rowsPerImage (${s.rowsPerImage}) must be at least ${s.height} for ${this.format}`);let{bytesPerPixel:c}=a;if(c&&s.bytesPerRow%c!==0)throw new Error(`bytesPerRow (${s.bytesPerRow}) must be a multiple of bytesPerPixel (${c}) for ${this.format}`);return s}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),o=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:n,depthOrArrayLayers:o}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:n,height:o,depthOrArrayLayers:i}=this._getMipLevelSize(t);e+=Bt.computeMemoryLayout({format:this.format,width:n,height:o,depth:i,byteAlignment:1}).byteLength}return e*this.samples}static _normalizeOptions(e,t,n){for(let o in t)n[o]=e[o]===void 0?t[o]:e[o];return n}static defaultProps={...he.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"}};var Ea=Le.DEBUG_DATA_MAX_LENGTH,we=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:o,ownsBuffer:i=!0,...s}=t;if(o&&o.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(o&&(s.byteLength!==void 0||s.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||o?.id||Pt("dynamic-buffer"),u={...s,id:a,usage:s.usage??o?.usage,indexType:s.indexType??o?.indexType};(u.usage||0)&Le.INDEX&&!u.indexType&&(s.data instanceof Uint32Array?u.indexType="uint32":s.data instanceof Uint16Array?u.indexType="uint16":s.data instanceof Uint8Array&&(u.indexType="uint8")),delete u.data,delete u.byteOffset,this.device=e,this.id=a,this.props=u,this.usage=u.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:Ea,this._ownsBuffer=i,this._buffer=o??this.device.createBuffer({...s,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),s.data&&this._writeDebugData(s.data,s.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 o=null;await this._buffer.mapAndWriteAsync(async(i,s)=>{await e(i,s),o=new Uint8Array(i.slice(0,n))},t,n),this._touch(),o&&this._writeDebugData(o,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 o=null,i=await this._buffer.mapAndReadAsync(async(s,a)=>(o=new Uint8Array(s.slice(0)),await e(s,a)),t,n);return o&&this._writeDebugData(o,t)&&this._touch(),i}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let o=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),i=this._buffer,s=this.debugData.slice(0),{data:a,byteOffset:u,...c}=this.props,d=this.device.createBuffer({...c,byteLength:t});return n&&o>0&&this._copyBufferContents(i,d,o),this._buffer=d,this._resetDebugData(t),n&&s.byteLength>0&&this._writeDebugData(s,0),this._ownsBuffer&&i.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 o=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,i=this.device.createCommandEncoder();i.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:o}),this.device.submit(i.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),o=new Uint8Array(this.debugData),i=Math.min(n.byteLength,o.byteLength-t);return o.set(n.subarray(0,i),t),i>0}};var An={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function Zt(r){return r?Array.isArray(r)?r[0]??null:r:null}function di(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=Zt(t);if(!n)return null;let{width:o}=Jt(n);return{width:o,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=Zt(t);return n?Jt(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=Zt(t[0]);return n?Jt(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let o=t[n],i=Zt(o);return i?Jt(i):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],o=Object.keys(n)[0]??null;if(!o)return null;let i=Zt(n[o]);return i?Jt(i):null}default:return null}}function Jt(r){if(Qt(r))return kr(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 Pa(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function Ca(r){return ArrayBuffer.isView(r)}function _n(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 fi(r){let e=An[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function La(r,e){return 6*r+fi(e)}function Fn(r){throw new Error("setTexture1DData not supported in WebGL.")}function Ba(r){return Array.isArray(r)?r:[r]}function ft(r,e,t,n){let o=Ba(e),i=r,s=[];for(let a=0;a<o.length;a++){let u=o[a];if(Qt(u))s.push({type:"external-image",image:u,z:i,mipLevel:a});else if(Pa(u))s.push({type:"texture-data",data:u,textureFormat:_n(u),z:i,mipLevel:a});else if(Ca(u)&&t)s.push({type:"texture-data",data:{data:u,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:i,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return s}function Rn(r){let e=[];for(let t=0;t<r.length;t++)e.push(...ft(t,r[t]));return e}function Mn(r){let e=[];for(let t=0;t<r.length;t++)e.push(...ft(t,r[t]));return e}function Vn(r){let e=[];for(let[t,n]of Object.entries(r)){let o=fi(t);e.push(...ft(o,n))}return e}function Nn(r){let e=[];return r.forEach((t,n)=>{for(let[o,i]of Object.entries(t)){let s=La(n,o);e.push(...ft(s,i))}}),e}var Je=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=Pt("dynamic-texture"),o=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((i,s)=>{this.resolveReady=i,this.rejectReady=s}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(o)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?Oa({...t,width:e.width,height:e.height,format:e.format}):[],o="format"in e&&e.format!==void 0,i="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 g=di(t);return g||{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 u=Ga(this.device,n,a,{format:o?e.format:void 0}),c=u.format??this.props.format,d={...this.props,...a,format:c,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(c)&&!i&&(d.usage=ne.SAMPLE|ne.COPY_DST);let f=this.props.mipmaps&&!u.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(c);if(this.device.type==="webgpu"&&f){let g=this.props.dimension==="3d"?ne.SAMPLE|ne.STORAGE|ne.COPY_DST|ne.COPY_SRC:ne.SAMPLE|ne.RENDER|ne.COPY_DST|ne.COPY_SRC;d.usage|=g}let l=this.device.getMipLevelCount(d.width,d.height),h=u.hasExplicitMipChain?u.mipLevels:this.props.mipLevels==="auto"?l:Math.max(1,Math.min(l,this.props.mipLevels??1)),m={...d,mipLevels:h};this._texture=this.device.createTexture(m),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),u.subresources.length&&this._setTextureSubresources(u.subresources),this.props.mipmaps&&!u.hasExplicitMipChain&&!f&&xe.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),f&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),xe.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()):xe.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof Ze?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,o=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:o}),s=this.device.createBuffer({byteLength:i.byteLength,usage:Le.COPY_DST|Le.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:o},s);let a=this.device.createFence();return await a.signaled,a.destroy(),s}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,o=e.depthOrArrayLayers??this.texture.depth,i=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:o}),s=await this.readBuffer(e),a=await s.readAsync(0,i.byteLength);return s.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(),xe.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=An[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=Fn(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=ft(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Rn(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=Mn(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=Vn(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=Nn(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:o}=t;switch(t.type){case"external-image":let{image:i,flipY:s}=t;this.texture.copyExternalImage({image:i,z:n,mipLevel:o,flipY:s});break;case"texture-data":let{data:a,textureFormat:u}=t;if(u&&u!==this.texture.format)throw new Error(`${this} mip level ${o} uses format "${u}" 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:o});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await zn(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&xe.warn(`${this} already destroyed`)}_checkReady(){this.isReady||xe.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...ne.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function Oa(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 Fn(r.data);case"2d":return ft(0,r.data,e,t);case"3d":return Rn(r.data);case"2d-array":return Mn(r.data);case"cube":return Vn(r.data);case"cube-array":return Nn(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function Ga(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let o=new Map;for(let d of e){let f=o.get(d.z)??[];f.push(d),o.set(d.z,f)}let i=e.some(d=>d.mipLevel>0),s=n.format,a=Number.POSITIVE_INFINITY,u=[];for(let[d,f]of o){let l=[...f].sort((w,S)=>w.mipLevel-S.mipLevel),h=l[0];if(!h||h.mipLevel!==0)throw new Error(`DynamicTexture: slice ${d} is missing mip level 0`);let m=hi(r,h);if(m.width!==t.width||m.height!==t.height)throw new Error(`DynamicTexture: slice ${d} base level dimensions ${m.width}x${m.height} do not match expected ${t.width}x${t.height}`);let g=li(h);if(g){if(s&&s!==g)throw new Error(`DynamicTexture: slice ${d} base level format "${g}" does not match texture format "${s}"`);s=g}let y=s&&r.isTextureFormatCompressed(s)?Da(r,m.width,m.height,s):r.getMipLevelCount(m.width,m.height),p=0;for(let w=0;w<l.length;w++){let S=l[w];if(!S||S.mipLevel!==w||w>=y)break;let v=hi(r,S),T=Math.max(1,m.width>>w),b=Math.max(1,m.height>>w);if(v.width!==T||v.height!==b)break;let P=li(S);if(P&&(s||(s=P),P!==s))break;p++,u.push(S)}a=Math.min(a,p)}let c=Number.isFinite(a)?Math.max(1,a):1;return{subresources:u.filter(d=>d.mipLevel<c),mipLevels:c,format:s,hasExplicitMipChain:i}}function li(r){if(r.type==="texture-data")return r.textureFormat??_n(r.data)}function hi(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 Da(r,e,t,n){let{blockWidth:o=1,blockHeight:i=1}=r.getTextureFormatInfo(n),s=1;for(let a=1;;a++){let u=Math.max(1,e>>a),c=Math.max(1,t>>a);if(u<o||c<i)break;s++}return s}async function zn(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(zn));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(zn)),n=Object.keys(e),o={};for(let i=0;i<n.length;i++)o[n[i]]=t[i];return o}return r}var er=R(A(),1),mi=/^vertex-list<([^<>]+)>$/,pi=/^value-list<([^<>]+)>$/,Fa=/^fixed-size-list<([^<>,]+),([1-9][0-9]*)>$/;function et(r){return mi.test(r)}function tt(r){return pi.test(r)}function gi(r){let e=mi.exec(r),t=pi.exec(r),o=yi(r)?.elementFormat??e?.[1]??t?.[1]??r;try{er.vertexFormatDecoder.getVertexFormatInfo(o)}catch{throw new Error(`Unsupported GPUVector format ${r}`)}return o}function I(r){let e=gi(r),t=et(r),n=tt(r),o=yi(r),i=er.vertexFormatDecoder.getVertexFormatInfo(e),s=i.byteLength*(o?.listSize??1);if(!Number.isSafeInteger(s))throw new Error(`Unsupported GPUVector format ${r}`);let a=i.type,u=i.normalized,c=Ra(a,u);return{format:r,elementFormat:e,vertexList:t,valueList:n,fixedSizeList:!!o,...o?{listSize:o.listSize}:{},type:a,signedDataType:Ma(e,a),primitiveType:c,components:i.components,elementByteLength:i.byteLength,byteLength:s,integer:i.integer,signed:i.signed,normalized:u,...i.webglOnly?{webglOnly:!0}:{}}}function yi(r){let e=Fa.exec(r);if(!e)return;let t=Number(e[2]);if(!Number.isSafeInteger(t))return;let n=e[1];try{let o=er.vertexFormatDecoder.getVertexFormatInfo(n);if(!Number.isSafeInteger(t*o.components)||!Number.isSafeInteger(t*o.byteLength))return}catch{return}return{elementFormat:n,listSize:t}}function Ra(r,e){if(e)return"f32";switch(r){case"float32":return"f32";case"float16":return"f16";case"uint8":case"uint16":case"uint32":return"u32";case"sint8":case"sint16":case"sint32":return"i32";default:throw new Error(`Unsupported GPUVector component type ${r}`)}}function Ma(r,e){if(r==="unorm10-10-10-2")return"uint32";switch(e){case"unorm8":return"uint8";case"snorm8":return"sint8";case"unorm16":return"uint16";case"snorm16":return"sint16";default:return e}}var Wn=R(A(),1),tr=class{buffer;format;length;byteOffset;byteStride;constructor(e){let t=Wn.vertexFormatDecoder.getVertexFormatInfo(e.format).byteLength,n=e.byteOffset??0,o=e.byteStride??t;if(jn(e.length,"GPUDataView length"),jn(n,"GPUDataView byteOffset"),jn(o,"GPUDataView byteStride"),o<t)throw new Error(`GPUDataView byteStride ${o} is smaller than ${e.format} byte length ${t}`);let i=e.length===0?0:(e.length-1)*o+t,s=n+i;if(!Number.isSafeInteger(i)||!Number.isSafeInteger(s))throw new Error("GPUDataView byte range must use safe integers");if(s>e.buffer.byteLength)throw new Error("GPUDataView exceeds its backing buffer byte length");this.buffer=e.buffer,this.format=e.format,this.length=e.length,this.byteOffset=n,this.byteStride=o}get elementByteLength(){return Wn.vertexFormatDecoder.getVertexFormatInfo(this.format).byteLength}get byteLength(){return this.length===0?0:(this.length-1)*this.byteStride+this.elementByteLength}};function jn(r,e){if(!Number.isSafeInteger(r)||r<0)throw new Error(`${e} must be a non-negative safe integer`)}var Ot=R(A(),1);function _r(r){return!!(r&&typeof r=="object"&&r.type==="struct")}function xi(r,e){let t=Object.entries(r);if(t.length===0)throw new Error("GPUData struct format must declare at least one field");return e==="packed"?Va(t):Na(t)}function Va(r){let e=[],t=0,n=0;for(let[o,i]of r){let s=Ot.vertexFormatDecoder.getVertexFormatInfo(i);if(s.webglOnly)throw new Error(`Packed GPUData struct field "${o}" uses WebGL-only format ${i}`);t=bi(t,Math.min(4,s.byteLength)),e.push([o,Object.freeze({format:i,byteOffset:t,byteLength:s.byteLength})]),t+=s.byteLength,n+=s.components}return Object.freeze({type:"struct",layout:"packed",fields:Object.freeze(Object.fromEntries(e)),components:n,byteStride:bi(t,4),rowByteLength:t})}function Na(r){let e=Object.fromEntries(r.map(([s,a])=>[s,za(a)])),t=(0,Ot.makeShaderBlockLayout)(e,{layout:"wgsl-storage"}),n=[],o=0,i=0;for(let[s,a]of r){let u=Ot.vertexFormatDecoder.getVertexFormatInfo(a),c=t.fields[s].offset*4;n.push([s,Object.freeze({format:a,byteOffset:c,byteLength:u.byteLength})]),o=Math.max(o,c+u.byteLength),i+=u.components}return Object.freeze({type:"struct",layout:"wgsl-storage",fields:Object.freeze(Object.fromEntries(n)),components:i,byteStride:t.byteLength,rowByteLength:o})}function za(r){let e=Ot.vertexFormatDecoder.getVertexFormatInfo(r);switch(e.type){case"float32":return Ar("f32",e.components);case"sint32":return Ar("i32",e.components);case"uint32":return Ar("u32",e.components);default:{let t=Math.ceil(e.byteLength/4);return Ar("u32",t)}}}function Ar(r,e){return e===1?r:`vec${e}<${r}>`}function bi(r,e){return Math.ceil(r/e)*e}var Hn=class{buffer;ownsDataBuffer;constructor(e,t){this.buffer=e,this.ownsDataBuffer=t}get ownsBuffer(){return this.ownsDataBuffer}transferBufferOwnership(e){if(e.buffer!==this.buffer)throw new Error("GPUData ownership can only be transferred to the same buffer");e.ownsDataBuffer=this.ownsDataBuffer,this.ownsDataBuffer=!1}destroy(){this.ownsDataBuffer&&(this.buffer.destroy(),this.ownsDataBuffer=!1)}},qn=class extends Hn{dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;readbackMetadata;valueOffsets;nullBitmap;valueByteLength;constructor(e){let{buffer:t,format:n,length:o,valueLength:i,stride:s,byteOffset:a=0,byteStride:u,rowByteLength:c,ownsBuffer:d=!1,readbackMetadata:f,valueOffsets:l,nullBitmap:h,valueByteLength:m,dataType:g}=e;super(t,d);let y;n?typeof n=="string"?y=n:y=xi(n,e.layout??"wgsl-storage"):y=void 0;let p=_r(y)?y:void 0,w=typeof y=="string"?I(y):void 0;if(this.dataType=g,this.format=y,this.length=o,this.valueLength=i??o*(w?.listSize??1),this.stride=s??(w?w.components*(w.listSize??1):void 0)??p?.components??u??c??1,this.byteOffset=a,this.rowByteLength=c??p?.rowByteLength??w?.byteLength??u??this.stride,this.byteStride=u??p?.byteStride??this.rowByteLength,w?.fixedSizeList){let S=o*w.listSize;if(!Number.isSafeInteger(o)||o<0||!Number.isSafeInteger(S)||!Number.isSafeInteger(this.byteOffset)||this.byteOffset<0||!Number.isSafeInteger(this.byteStride)||!Number.isSafeInteger(this.rowByteLength)||!Number.isSafeInteger(this.stride))throw new Error("GPUData fixed-size-list row layout must use safe non-negative integers");if(this.valueLength!==S)throw new Error("GPUData fixed-size-list valueLength must equal its flattened row elements");if(this.stride<w.components*w.listSize)throw new Error("GPUData fixed-size-list stride cannot truncate its row components");if(this.rowByteLength<w.byteLength)throw new Error("GPUData fixed-size-list rowByteLength cannot truncate its row payload");if(this.byteStride<this.rowByteLength)throw new Error("GPUData fixed-size-list byteStride cannot overlap its row payload");let v=o===0?0:(o-1)*this.byteStride+this.rowByteLength,T=this.byteOffset+v;if(!Number.isSafeInteger(v)||!Number.isSafeInteger(T))throw new Error("GPUData fixed-size-list byte range must use safe integers");if(T>t.byteLength)throw new Error("GPUData fixed-size-list exceeds its backing buffer byte length")}if(p){if(this.rowByteLength<p.rowByteLength)throw new Error(`GPUData rowByteLength ${this.rowByteLength} is smaller than struct format row byte length ${p.rowByteLength}`);if(this.byteStride<Math.max(p.byteStride,this.rowByteLength))throw new Error(`GPUData byteStride ${this.byteStride} is smaller than its struct row layout`)}this.readbackMetadata=f,this.valueOffsets=l,this.nullBitmap=h,this.valueByteLength=m}getChild(e){if(!_r(this.format))return null;let t=this.format.fields[e];return t?new tr({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}getChildAt(e){if(!_r(this.format))return null;let t=Object.values(this.format.fields)[e];return t?new tr({buffer:this.buffer,format:t.format,length:this.length,byteOffset:this.byteOffset+t.byteOffset,byteStride:this.byteStride}):null}},Gt=qn;function _e(r){let e=0;return Object.freeze(r.map(t=>{let n=Object.freeze({offset:e,length:t.length,data:t});return e+=t.length,n}))}var z=class{name;dataType;format;length;valueLength;stride;byteOffset;byteStride;rowByteLength;bufferLayout;data=[];device;bufferProps;isAppendable=!1;ownsDataChunks=!0;ownedVectors=[];appendableByteLength=0;get chunks(){return _e(this.data)}constructor(e){switch(e.type){case"buffer":{let{name:t,buffer:n,format:o,length:i,valueLength:s,byteOffset:a=0,ownsBuffer:u=!1}=e,{stride:c,byteStride:d,rowByteLength:f,listSize:l}=wi(e),h=s??i*(l??1);this.name=t,this.dataType=e.dataType,this.format=o,this.length=i,this.valueLength=h,this.stride=c,this.byteOffset=a,this.byteStride=d,this.rowByteLength=f,this.data.push(new Gt({buffer:n,format:o,length:i,valueLength:h,stride:c,byteOffset:a,byteStride:d,rowByteLength:f,ownsBuffer:u,dataType:e.dataType}));return}case"interleaved":{let{name:t,buffer:n,format:o,length:i,valueLength:s,byteOffset:a=0,byteStride:u,attributes:c,ownsBuffer:d=!1}=e,f=o?I(o):void 0,l=s??i*(f?.listSize??1),h=f?.fixedSizeList?f.components*f.listSize:u,m=f?.fixedSizeList?f.byteLength:u;this.name=t,this.dataType=e.dataType,this.format=o,this.length=i,this.valueLength=l,this.stride=h,this.byteOffset=a,this.byteStride=u,this.rowByteLength=m,this.bufferLayout={name:t,byteStride:u,attributes:c},this.data.push(new Gt({buffer:n,format:o,length:i,valueLength:l,stride:h,byteOffset:a,byteStride:u,rowByteLength:m,ownsBuffer:d,dataType:e.dataType}));return}case"data":{let t=e.format??ja(e.data),n=t?I(t):void 0,{name:o,data:i,stride:s=i[0]?.stride??(n?n.components*(n.listSize??1):1),valueLength:a=i.reduce((l,h)=>l+h.valueLength,0),byteStride:u=i[0]?.byteStride??n?.byteLength,rowByteLength:c=i[0]?.rowByteLength??n?.byteLength,bufferLayout:d,ownsData:f=!1}=e;if(u===void 0||c===void 0)throw new Error("GPUVector requires format or explicit byte layout metadata");t&&Wa(i,t),this.name=o,this.dataType=e.dataType,this.format=t,this.length=i.reduce((l,h)=>l+h.length,0),this.valueLength=a,this.stride=s,this.byteOffset=i.length===1?i[0].byteOffset:0,this.byteStride=u,this.rowByteLength=c,this.bufferLayout=d,this.ownsDataChunks=f,this.data.push(...i);return}case"appendable":{let{name:t,device:n,format:o,valueLength:i=0,bufferProps:s}=e,{stride:a,byteStride:u,rowByteLength:c}=wi(e);this.name=t,this.dataType=e.dataType,this.format=o,this.length=0,this.valueLength=i,this.stride=a,this.byteOffset=0,this.byteStride=u,this.rowByteLength=c,this.device=n,this.bufferProps=s,this.isAppendable=!0;return}}}get ownsBuffer(){return this.ownsDataChunks&&this.data.some(e=>e.ownsBuffer)||this.ownedVectors.some(e=>e.ownsBuffer)}get capacityRows(){return this.isAppendable?this.length:void 0}get appendedByteLength(){return this.appendableByteLength}addData(e){if(this.format&&e.format!==this.format)throw new Error("GPUVector.addData() requires matching formats");if(e.byteStride!==this.byteStride)throw new Error("GPUVector.addData() requires matching byteStride");if(e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.addData() requires matching rowByteLength");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this}appendDataChunk(e,t=this.appendableByteLength+e.buffer.byteLength){if(!this.isAppendable)throw new Error("GPUVector.appendDataChunk() requires appendable vector storage");if(this.format&&e.format!==this.format)throw new Error("GPUVector.appendDataChunk() requires matching formats");if(e.byteStride!==this.byteStride||e.rowByteLength!==this.rowByteLength)throw new Error("GPUVector.appendDataChunk() requires matching byte layout metadata");return this.data.push(e),this.length+=e.length,this.valueLength+=e.valueLength,this.appendableByteLength=t,this}resetLastBatch(){if(!this.isAppendable)throw new Error("GPUVector.resetLastBatch() requires appendable vector storage");for(let e of this.data.splice(0))e.destroy();return this.length=0,this.valueLength=0,this.appendableByteLength=0,this}retainOwnedVectors(e){return this.ownedVectors.push(...e),this}transferBufferOwnership(e){let t=this.data[0],n=e.data[0];if(!t||!n||t.buffer!==n.buffer)throw new Error("GPUVector ownership can only be transferred to the same buffer");t.transferBufferOwnership(n)}destroy(){if(this.ownsDataChunks)for(let e of this.data)e.destroy();for(let e of this.ownedVectors.splice(0))e.destroy()}};function wi(r){let e=r.format?I(r.format):void 0,t=r.rowByteLength??(e?.fixedSizeList?e.byteLength:r.byteStride)??e?.byteLength;if(t===void 0)throw new Error("GPUVector requires format or explicit rowByteLength");return{stride:r.stride??(e?e.components*(e.listSize??1):1),byteStride:r.byteStride??t,rowByteLength:t,...e?.listSize?{listSize:e.listSize}:{}}}function ja(r){return r[0]?.format}function Wa(r,e){if(r.find(n=>n.format!==e))throw new Error("GPUVector data chunks must share the declared format")}var Yn=R(A(),1);var rr=R(A(),1);var nr=class{buffer;format;length;valueLength;byteOffset;byteStride;rowByteLength;valueOffsets;nullBitmap;constructor(e){let t=I(e.format),n=ArrayBuffer.isView(e.buffer)?e.buffer:void 0;this.buffer=n?n.buffer:e.buffer,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength??e.length*(t.listSize??1);let o=e.byteOffset??0;this.byteOffset=(n?.byteOffset??0)+o,this.rowByteLength=e.rowByteLength??t.byteLength,this.byteStride=e.byteStride??this.rowByteLength,this.valueOffsets=e.valueOffsets,this.nullBitmap=e.nullBitmap;let i=t.vertexList||t.valueList,s=i?this.valueLength:this.length;(0,rr.assert)([this.length,this.valueLength,o,this.rowByteLength,this.byteStride].every(a=>Number.isSafeInteger(a)&&a>=0)),(0,rr.assert)(this.rowByteLength>=t.byteLength&&this.byteStride>=this.rowByteLength),(0,rr.assert)(i||this.valueLength===this.length*(t.listSize??1)),(0,rr.assert)(o+(s?(s-1)*this.byteStride+this.rowByteLength:0)<=e.buffer.byteLength)}};var Ti=R(A(),1),Te=class{name;format;data;length;valueLength;constructor(e){(0,Ti.assert)(e.data.every(t=>t.format===e.format)),this.name=e.name??"",this.format=e.format,this.data=Object.freeze([...e.data]),this.length=this.data.reduce((t,n)=>t+n.length,0),this.valueLength=this.data.reduce((t,n)=>t+n.valueLength,0)}};var or=class{compare;values=[];constructor(e){this.compare=e}peek(){return this.values[0]}push(e){let t=this.values.length;for(this.values.push(e);t>0;){let n=Math.floor((t-1)/2);if(this.compare(this.values[n],e)<=0)break;this.values[t]=this.values[n],t=n}this.values[t]=e}pop(){let e=this.values[0],t=this.values.pop();if(this.values.length&&t!==void 0){let n=0;for(;n*2+1<this.values.length;){let o=n*2+1;if(o+1<this.values.length&&this.compare(this.values[o+1],this.values[o])<0&&o++,this.compare(t,this.values[o])<=0)break;this.values[n]=this.values[o],n=o}this.values[n]=t}return e}};var rt=R(A(),1);function Ci(r){let e=Gi(r.nodes),t=Di(e,r.buffers.values()),n=Ii(e,r.textures.values()),o=new Map,i=new Map,s=[];try{for(let a of t){a.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(a)}`,byteLength:a.byteLength,usage:a.usage});for(let u of a.handles)o.set(u,a.buffer)}for(let a of n){a.texture=r.device.createTexture({...a.descriptor,id:`${r.id}-transient-texture-${n.indexOf(a)}`});for(let u of a.handles)i.set(u,a.texture)}for(let a of e)s.push({node:a,executable:a.compile({device:r.device})})}catch(a){for(let u of s)u.executable.destroy?.();for(let u of t)u.buffer?.destroy();for(let u of n)u.texture?.destroy();throw a}return Bi(r,e,s,o,i,t,n)}async function Li(r){let e=Gi(r.nodes),t=Di(e,r.buffers.values()),n=Ii(e,r.textures.values()),o=new Map,i=new Map;try{for(let h of t){h.buffer=r.device.createBuffer({id:`${r.id}-transient-buffer-${t.indexOf(h)}`,byteLength:h.byteLength,usage:h.usage});for(let m of h.handles)o.set(m,h.buffer)}for(let h of n){h.texture=r.device.createTexture({...h.descriptor,id:`${r.id}-transient-texture-${n.indexOf(h)}`});for(let m of h.handles)i.set(m,h.texture)}let s=rt.PipelineFactory.beginAsyncCompilation(r.device),a=e.map(async h=>({node:h,executable:h.compileAsync?await h.compileAsync({device:r.device}):h.compile({device:r.device})}));rt.PipelineFactory.endAsyncCompilation(r.device,s);let[u,c]=await Promise.all([Promise.allSettled(a),Promise.allSettled(s)]),d=[],f=c.find(h=>h.status==="rejected"),l=f?.status==="rejected"?f.reason:void 0;for(let h of u)h.status==="fulfilled"?d.push(h.value):l??=h.reason;if(l){for(let h of d)h.executable.destroy?.();throw l}return Bi(r,e,d,o,i,t,n)}catch(s){for(let a of t)a.buffer?.destroy();for(let a of n)a.texture?.destroy();throw s}}function Bi(r,e,t,n,o,i,s){let a=Array.from(r.buffers.values()),u=a.filter(E=>!E.transient),c=a.filter(E=>E.transient),d=Dt(u.map(E=>E.byteLength),"imported buffer capacities"),f=Dt(c.map(E=>E.byteLength),"logical transient buffer capacities"),l=lt(d,f,"logical buffer capacities"),h=Dt(i.map(E=>E.byteLength),"physical transient buffer capacities"),m=Math.max(0,f-h),g=Array.from(r.textures.values()),y=g.filter(E=>!E.transient),p=g.filter(E=>E.transient),w=Dt(y.map(Zn),"imported texture estimates"),S=Dt(p.map(Zn),"logical transient texture estimates"),v=lt(w,S,"logical texture estimates"),T=Dt(s.map(E=>E.byteLength),"physical transient texture estimates"),b=Math.max(0,S-T),P={nodeOrder:e.map(E=>E.id),importedBufferCount:u.length,importedBufferBytes:d,logicalBufferCount:a.length,logicalBufferBytes:l,logicalTransientBufferCount:c.length,physicalTransientBufferCount:i.length,logicalTransientBytes:f,physicalTransientBytes:h,reusedTransientBytes:m,reusePercentage:f>0?m/f*100:0,importedTextureCount:y.length,importedTextureBytes:w,logicalTextureCount:g.length,logicalTextureBytes:v,logicalTransientTextureCount:p.length,physicalTransientTextureCount:s.length,logicalTransientTextureBytes:S,physicalTransientTextureBytes:T,reusedTransientTextureBytes:b,textureReusePercentage:S>0?b/S*100:0,logicalResourceBytes:lt(l,v,"logical resource estimates"),physicalTransientResourceBytes:lt(h,T,"physical transient resource estimates")},B=qa(r.device,a,e);return{device:r.device,id:r.id,buffers:new Map(r.buffers),textures:new Map(r.textures),externalTextures:new Map(r.externalTextures),compiledNodes:t,transientBuffers:n,transientTextures:o,bufferTransientAllocations:i,textureTransientAllocations:s,stats:P,preflight:B}}function Ha(r){if("buffer"in r){let t=r.buffer,n="buffer"in t?t:void 0;return Object.freeze({id:n?n.buffer.id:t.id,kind:"buffer",usage:r.usage,byteOffset:n?.byteOffset??0,byteLength:n?n.length===0?0:(n.length-1)*n.byteStride+n.rowByteLength:t.byteLength,...n?{format:n.format,length:n.length}:{}})}let e="texture"in r?r.texture:r.externalTexture;return Object.freeze({id:"texture"in e?e.texture.id:e.id,kind:"externalTexture"in r?"external-texture":"texture",usage:r.usage,width:e.width,height:e.height,..."texture"in e?{baseMipLevel:e.baseMipLevel,baseArrayLayer:e.baseArrayLayer,mipLevelCount:e.mipLevelCount,arrayLayerCount:e.arrayLayerCount,aspect:e.aspect}:{},..."format"in e?{format:e.format,depth:e.depth}:{}})}function qa(r,e,t){let n=t.map(a=>{let u=a.workload??{};return Object.freeze({id:a.id,...a.description===void 0?{}:{description:a.description},type:a.type,resources:Object.freeze((a.resources??[]).map(Ha)),...u.operation?{operation:u.operation}:{},...u.variant?{variant:u.variant}:{},...a.publication?{publication:Object.freeze({...a.publication})}:{},...a.condition?{condition:Object.freeze(a.condition.source==="cpu"?{id:a.condition.id,source:"cpu",mode:"skip"}:{id:a.condition.id,source:"gpu",mode:"indirect",bufferId:a.condition.buffer.id,byteOffset:a.condition.byteOffset??0})}:{},commandCount:u.commandCount??0,maximumWorkgroupCount:u.maximumWorkgroupCount??0,maximumInvocationCount:u.maximumInvocationCount??0,readByteLength:u.readByteLength??0,writeByteLength:u.writeByteLength??0})}),o=e.reduce((a,u)=>Math.max(a,u.byteLength),0),i=t.reduce((a,u)=>{for(let c of u.resources??[])nt(c)&&(c.usage==="storage-read"||c.usage==="storage-write"||c.usage==="storage-read-write")&&(a=Math.max(a,Kn(c.buffer).size));return a},0),s=a=>n.reduce((u,c)=>{let d=c[a];return typeof d=="number"?lt(u,d,"workload estimates"):u},0);return Object.freeze({nodes:Object.freeze(n),annotatedNodeCount:t.filter(a=>a.workload!==void 0).length,conditionalNodeCount:t.filter(a=>a.condition!==void 0).length,commandCount:s("commandCount"),maximumWorkgroupCount:s("maximumWorkgroupCount"),maximumInvocationCount:s("maximumInvocationCount"),readByteLength:s("readByteLength"),writeByteLength:s("writeByteLength"),largestBufferByteLength:o,largestStorageBufferBindingByteLength:i,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,fitsDeviceLimits:o<=r.limits.maxBufferSize&&i<=r.limits.maxStorageBufferBindingSize})}function ve(r){return"buffer"in r?r.buffer:r}function Fe(r){return"texture"in r?r.texture:r}function nt(r){return"buffer"in r}function ir(r){return"texture"in r}function Oi(r){if(r.type==="copy")return;let e=(r.resources??[]).filter(t=>nt(t)&&(t.usage==="storage-read"||t.usage==="storage-write"||t.usage==="storage-read-write"));for(let t=0;t<e.length;t++){let n=e[t];for(let o=t+1;o<e.length;o++){let i=e[o];if(n.buffer===i.buffer||ve(n.buffer)!==ve(i.buffer)||!Qn(n.usage)&&!Qn(i.usage))continue;let s=Kn(n.buffer),a=Kn(i.buffer);if(s.offset<a.offset+a.size&&a.offset<s.offset+s.size){let u=ve(n.buffer);throw new Error(`GPUCommandGraph node "${r.id}" has overlapping writable storage bindings for buffer "${u.id}" (${vi(s)} and ${vi(a)}). Bind the shared range once or align the views to non-overlapping storage binding ranges.`)}}}}function Kn(r){if(!("buffer"in r))return{offset:0,size:r.byteLength};let e=256,t=Math.floor(r.byteOffset/e)*e,n=r.byteOffset-t,o=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:t,size:n+Math.max(o,r.rowByteLength)}}function vi(r){return`${r.offset}\u2013${r.offset+r.size} bytes`}function Ya(r){return r==="storage-read"||r==="storage-read-write"||r==="uniform"||r==="copy-source"||r==="indirect"||r==="vertex"||r==="index"}function Qn(r){return r==="storage-write"||r==="storage-read-write"||r==="copy-destination"}function Si(r){return r==="sampled"||r==="storage-read"||r==="storage-read-write"||r==="render-attachment"||r==="copy-source"}function Xn(r){return r==="storage-write"||r==="storage-read-write"||r==="render-attachment"||r==="copy-destination"}function Gi(r){let e=new Map(r.map(f=>[f.id,f])),t=new Map,n=new Map,o=new Map,i=new Map;for(let f of r){let l=new Set(f.dependsOn??[]);for(let h of l)if(!e.has(h))throw new Error(`GPUCommandGraph node "${f.id}" depends on missing node "${h}"`);for(let h of f.resources??[])if(nt(h)){let m=ve(h.buffer);if(Ya(h.usage)){let g=n.get(m);g&&l.add(g);let y=o.get(m)??new Set;y.add(f.id),o.set(m,y)}if(Qn(h.usage)){let g=n.get(m);g&&l.add(g);for(let y of o.get(m)??[])y!==f.id&&l.add(y);o.set(m,new Set),n.set(m,f.id)}}else if(ir(h)){let m=Fe(h.texture),g=i.get(m)??[];for(let y of g)y.nodeId!==f.id&&Xa(y.resource,h)&&(Si(h.usage)&&Xn(y.resource.usage)||Xn(h.usage)&&(Si(y.resource.usage)||Xn(y.resource.usage)))&&l.add(y.nodeId);g.push({nodeId:f.id,resource:h}),i.set(m,g)}l.delete(f.id),t.set(f.id,l)}let s=r.map(()=>[]),a=new Map(r.map((f,l)=>[f.id,l])),u=r.map(f=>t.get(f.id).size);for(let[f,l]of r.entries())for(let h of t.get(l.id))s[a.get(h)].push(f);let c=u.flatMap((f,l)=>f===0?[l]:[]),d=[];for(;c.length;){let f=[];for(let l of c){d.push(r[l]);for(let h of s[l])--u[h]===0&&f.push(h)}c=f.sort((l,h)=>l-h)}if(d.length!==r.length)throw new Error("GPUCommandGraph contains a dependency cycle");return d}function Xa(r,e){let t=Fe(r.texture),n=Fe(e.texture);if(t!==n)return!1;let o=Ei(r.texture),i=Ei(e.texture);return Ka(o.aspect,i.aspect)&&Pi(o.baseMipLevel,o.mipLevelCount,i.baseMipLevel,i.mipLevelCount)&&Pi(o.baseArrayLayer,o.arrayLayerCount,i.baseArrayLayer,i.arrayLayerCount)}function Ei(r){return"texture"in r?r:{aspect:"all",baseMipLevel:0,mipLevelCount:r.mipLevels,baseArrayLayer:0,arrayLayerCount:r.dimension==="3d"?1:r.depth}}function Ka(r,e){return r==="all"||e==="all"||r===e}function Pi(r,e,t,n){return r<t+n&&t<r+e}function Di(r,e){let t=Ui(r,c=>nt(c)?ve(c.buffer):null),n=new Map;r.forEach((c,d)=>{if(!c.retainedBuffers?.length)return;let f=n.get(c.retainedBuffers);f?f.lastUse=d:n.set(c.retainedBuffers,{firstUse:d,lastUse:d})});for(let[c,d]of n)for(let f of c){if(!f.transient)continue;let l=t.get(f);t.set(f,{firstUse:Math.min(l?.firstUse??d.firstUse,d.firstUse),lastUse:Math.max(l?.lastUse??d.lastUse,d.lastUse)})}let o=[],i=Array.from(e).filter(c=>c.transient).map(c=>({buffer:c,lifetime:t.get(c)})).sort((c,d)=>(c.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(d.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)),s=new or((c,d)=>c.allocation.lastUse-d.allocation.lastUse||c.index-d.index),a=new Map,u=c=>{let d=c&(rt.Buffer.MAP_READ|rt.Buffer.MAP_WRITE),f=a.get(d);return f||(f=new or((l,h)=>l.allocation.byteLength-h.allocation.byteLength||l.index-h.index),a.set(d,f)),f};for(let{buffer:c,lifetime:d}of i){if(!d)continue;for(;s.peek()&&s.peek().allocation.lastUse<d.firstUse;){let h=s.pop();u(h.allocation.usage).push(h)}let f=u(c.usage).pop();f||(f={allocation:{byteLength:0,usage:0,lastUse:-1,handles:[]},index:o.length},o.push(f.allocation));let{allocation:l}=f;l.byteLength=Math.max(l.byteLength,c.byteLength),l.usage|=c.usage,l.lastUse=d.lastUse,l.handles.push(c),s.push(f)}return o}function Ii(r,e){let t=Ui(r,i=>ir(i)?Fe(i.texture):null),n=[],o=Array.from(e).filter(i=>i.transient).map(i=>({texture:i,lifetime:t.get(i)})).sort((i,s)=>(i.lifetime?.firstUse??Number.MAX_SAFE_INTEGER)-(s.lifetime?.firstUse??Number.MAX_SAFE_INTEGER));for(let{texture:i,lifetime:s}of o){if(!s)continue;let a=n.find(u=>u.lastUse<s.firstUse&&Za(u.descriptor,i));a||(a={descriptor:Qa(i),byteLength:Zn(i),lastUse:-1,handles:[]},n.push(a)),a.descriptor.usage|=i.usage,a.lastUse=s.lastUse,a.handles.push(i)}return n}function Ui(r,e){let t=new Map;return r.forEach((n,o)=>{for(let i of n.resources??[]){let s=e(i);if(!s||!("transient"in s)||!s.transient)continue;let a=t.get(s);a?a.lastUse=o:t.set(s,{firstUse:o,lastUse:o})}}),t}function Qa(r){return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:r.dimension,depth:r.depth,mipLevels:r.mipLevels,samples:r.samples}}function Za(r,e){return r.format===e.format&&r.width===e.width&&r.height===e.height&&r.dimension===e.dimension&&r.depth===e.depth&&r.mipLevels===e.mipLevels&&r.samples===e.samples}function Zn(r){let e=0;for(let n=0;n<r.mipLevels;n++)e=lt(e,rt.textureFormatDecoder.computeMemoryLayout({format:r.format,width:Math.max(1,r.width>>n),height:r.dimension==="1d"?1:Math.max(1,r.height>>n),depth:r.dimension==="3d"?Math.max(1,r.depth>>n):r.depth,byteAlignment:1}).byteLength,`texture "${r.id}" mip estimates`);let t=e*r.samples;if(!Number.isSafeInteger(t))throw new Error(`GPUCommandGraph texture "${r.id}" byte estimate exceeds safe integer range`);return t}function lt(r,e,t){let n=r+e;if(!Number.isSafeInteger(n))throw new Error(`GPUCommandGraph ${t} exceed safe integer range`);return n}function Dt(r,e){return r.reduce((t,n)=>lt(t,n,e),0)}var Re=class{id;byteLength;usage;transient;graph;defaultBuffer;constructor(e,t,n,o){this.graph=e,this.id=t.id,this.byteLength=t.byteLength,this.usage=t.usage,this.transient=n,this.defaultBuffer=o}},Ge=class{buffer;format;length;byteOffset;byteStride;rowByteLength;constructor(e,t){this.buffer=e,this.format=t.format,this.length=t.length,this.byteOffset=t.byteOffset,this.byteStride=t.byteStride,this.rowByteLength=t.rowByteLength}},G=class{chunks;id;name;format;length;valueLength;stride;byteStride;rowByteLength;data;constructor(e){if(this.id=e.id,this.name=e.name,this.format=e.format,this.length=e.length,this.valueLength=e.valueLength,this.stride=e.stride,this.byteStride=e.byteStride,this.rowByteLength=e.rowByteLength,e.data.some(t=>t.format!==e.format)||e.data.reduce((t,n)=>t+n.length,0)!==e.length)throw new Error(`${e.id} length must equal its ordered source chunks, with matching formats`);this.data=Object.freeze([...e.data]),this.chunks=_e(this.data)}},Se=class{id;format;width;height;usage;dimension;depth;mipLevels;samples;transient;frameScoped;graph;defaultTexture;constructor(e,t,n,o,i=!1){this.graph=e,this.id=t.id,this.format=t.format,this.width=t.width,this.height=t.height,this.usage=t.usage,this.dimension=t.dimension,this.depth=t.depth,this.mipLevels=t.mipLevels,this.samples=t.samples,this.transient=n,this.frameScoped=i,this.defaultTexture=o}},ot=class{id;width;height;graph;constructor(e,t){this.graph=e,this.id=t.id,this.width=t.width,this.height=t.height}},De=class{texture;format;dimension;aspect;baseMipLevel;mipLevelCount;baseArrayLayer;arrayLayerCount;width;height;depth;constructor(e,t){this.texture=e,this.format=e.format,this.dimension=t.dimension,this.aspect=t.aspect,this.baseMipLevel=t.baseMipLevel,this.mipLevelCount=t.mipLevelCount,this.baseArrayLayer=t.baseArrayLayer,this.arrayLayerCount=t.arrayLayerCount,this.width=t.width,this.height=t.height,this.depth=t.depth}};function Jn(r,e){switch(e.type){case"compute":{let{type:t,...n}=e;r.addComputePass(n);return}case"render":{let{type:t,...n}=e;r.addRenderPass(n);return}case"copy":{let{type:t,...n}=e;r.addCopyPass(n);return}}}function Me(r,e){for(let t of e)Jn(r,t)}function j(r){return{...r,type:"compute"}}var Ja=4,It=class{nodeCount;budget;plan;encodeNodeRange;nextStepIndex=0;currentPublishedProgress=0;constructor(e){Ri(e.budget),this.plan=e.plan,this.nodeCount=e.plan.nodeCount,this.budget=Object.freeze({...e.budget}),this.encodeNodeRange=e.encodeNodeRange}get completed(){return this.nextStepIndex>=this.plan.stepCount}get progress(){return this.plan.stepCount===0?1:this.nextStepIndex/this.plan.stepCount}get publishedProgress(){return this.currentPublishedProgress}encodeNext(e,t){if(this.completed)throw new Error("GPUCommandGraph execution has already completed");let n=this.plan.steps[this.nextStepIndex],o=this.encodeNodeRange(e,t,n.firstNodeIndex,n.nextNodeIndex);return this.nextStepIndex++,n.publishable&&(this.currentPublishedProgress=this.progress),{...n,encoding:o,progress:this.progress,completed:this.completed,publishedProgress:this.publishedProgress}}};function Rr(r,e,t={}){Ri(e);let n=t.latencyPriority??"normal",o=t.publicationPolicy??"final";if(!["interactive","normal","background"].includes(n))throw new Error(`GPUCommandGraph execution latency priority "${n}" is invalid`);if(!["final","progressive"].includes(o))throw new Error(`GPUCommandGraph execution publication policy "${o}" is invalid`);let i=r.nodes,s=[],a=0;for(;a<i.length;){let c=a,d=$i();for(;a<i.length;){let h=ki(d,i[a]);if(a>c&&Ai(h,e)||(d=h,a++,o==="progressive"&&i[a-1].publication)||eu(d,e))break}let f=Object.freeze(o==="progressive"?i.slice(c,a).flatMap(h=>h.publication?[h.publication]:[]):[]),l=a===i.length;s.push(Object.freeze({stepIndex:s.length,firstNodeIndex:c,nextNodeIndex:a,...d,exceedsBudget:Ai(d,e),latencyPriority:n,publications:f,publishable:l||f.length>0}))}let u=i.reduce((c,d)=>ki(c,d),$i());return Object.freeze({...u,annotatedNodeCount:r.annotatedNodeCount,stepCount:s.length,oversizedStepCount:s.filter(c=>c.exceedsBudget).length,latencyPriority:n,publicationPolicy:o,publicationCount:s.reduce((c,d)=>c+d.publications.length,0),steps:Object.freeze(s)})}function $i(){return{nodeCount:0,commandCount:0,maximumInvocationCount:0,readByteLength:0,writeByteLength:0,conditionalNodeCount:0}}function ki(r,e){return{nodeCount:r.nodeCount+1,commandCount:r.commandCount+e.commandCount,maximumInvocationCount:r.maximumInvocationCount+e.maximumInvocationCount,readByteLength:r.readByteLength+e.readByteLength,writeByteLength:r.writeByteLength+e.writeByteLength,conditionalNodeCount:r.conditionalNodeCount+(e.condition?1:0)}}function Ai(r,e){return r.maximumInvocationCount>e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>e.maximumWriteByteLength}function eu(r,e){return r.maximumInvocationCount>=e.maximumInvocationCount||e.maximumNodeCount!==void 0&&r.nodeCount>=e.maximumNodeCount||e.maximumCommandCount!==void 0&&r.commandCount>=e.maximumCommandCount||e.maximumReadByteLength!==void 0&&r.readByteLength>=e.maximumReadByteLength||e.maximumWriteByteLength!==void 0&&r.writeByteLength>=e.maximumWriteByteLength}function Ri(r){let e=[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]];for(let[t,n]of e)if(n!==void 0&&(!Number.isSafeInteger(n)||n<=0))throw new Error(`GPUCommandGraph execution ${t} must be a positive safe integer`)}function tu(r,e,t,n){let o=0;return{computePass:new Proxy(r,{get(s,a){if(a==="dispatch")return()=>{if(o>0)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`);o++,s.dispatchIndirect(e,t)};if(a==="dispatchIndirect")return()=>{throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must use dispatch(); the graph supplies its indirect command`)};let u=Reflect.get(s,a,s);return typeof u=="function"?u.bind(s):u}}),assertDispatched:()=>{if(o!==1)throw new Error(`GPUCommandGraph GPU-conditional compute node "${n}" must encode exactly one dispatch`)}}}var Ut=class{readResource;stats;canReadGPUTimings;nodes;constructor(e,t,n=e.filter(a=>a.stats.type==="compute"&&a.stats.condition?.outcome!=="skipped").length,o,i,s){this.readResource=s,this.nodes=e,this.canReadGPUTimings=e.some(c=>c.timestamp!==void 0);let a=e.filter(c=>c.stats.condition?.outcome!=="skipped"),u=a.filter(c=>c.stats.type==="compute").length;this.stats={cpuEncodeTimeMilliseconds:t,cpuEncodeStartTimeMilliseconds:o,cpuEncodeEndTimeMilliseconds:i,nodeCount:a.length,skippedNodeCount:e.length-a.length,computePassCount:n,coalescedComputeNodeCount:u-n,timestampedNodeCount:e.filter(c=>c.timestamp!==void 0).length,nodes:e.map(c=>c.stats)}}async readTimings(){let e=await Promise.all(this.nodes.map(async({stats:s,timestamp:a})=>{if(!a)return{...s};let{querySet:u,snapshot:c,beginIndex:d,endIndex:f}=a;if(u.device.type!=="webgpu")return{...s,gpuTimeMilliseconds:await u.readTimestampDuration(d,f)};let l=await(c??u).readResults({firstQuery:d,queryCount:f-d+1}),h=l[0],m=l[l.length-1];return{...s,gpuStartTimeMilliseconds:Number(h)/1e6,gpuEndTimeMilliseconds:Number(m)/1e6,gpuTimeMilliseconds:Number(m-h)/1e6}})),t=e.filter(s=>s.gpuTimeMilliseconds!==void 0),n=e.filter(s=>s.gpuStartTimeMilliseconds!==void 0),i=this.nodes.flatMap(s=>s.timestamp?.snapshot?.clockCorrelation?[s.timestamp.snapshot.clockCorrelation]:[]).sort((s,a)=>s.uncertaintyMilliseconds-a.uncertaintyMilliseconds)[0];return{...i?{clockCorrelation:i}:{},cpuEncodeStartTimeMilliseconds:this.stats.cpuEncodeStartTimeMilliseconds,cpuEncodeEndTimeMilliseconds:this.stats.cpuEncodeEndTimeMilliseconds,...n.length>0?{gpuStartTimeMilliseconds:Math.min(...n.map(s=>s.gpuStartTimeMilliseconds)),gpuEndTimeMilliseconds:Math.max(...n.map(s=>s.gpuEndTimeMilliseconds))}:{},cpuEncodeTimeMilliseconds:this.stats.cpuEncodeTimeMilliseconds,...t.length>0?{gpuTimeMilliseconds:t.reduce((s,a)=>s+(a.gpuTimeMilliseconds??0),0)}:{},nodes:e}}},to=class{device;id;autotuner;buffers=new Map;textures=new Map;externalTextures=new Map;importedBufferHandles=new Map;dynamicBufferHandles=new Map;nodes=[];nodeIds=new Set;compiled=!1;constructor(e,t={}){Fr(e,"construction"),this.device=e,this.id=t.id??"gpu-command-graph",this.autotuner=t.autotuner}importBuffer(e,t){this.assertMutable(),Fi(e,this.device),t&&Mi(t,e,this.device);let n=this.addBuffer(new Re(this,e,!1,t));if(t){let o=ur(t);this.importedBufferHandles.has(o)||this.importedBufferHandles.set(o,n),t instanceof we&&!this.dynamicBufferHandles.has(t)&&this.dynamicBufferHandles.set(t,n)}return n}createTransientBuffer(e){return this.assertMutable(),Fi(e,this.device),this.addBuffer(new Re(this,e,!0))}getUniqueResourceId(e){let t=e,n=1;for(;this.buffers.has(t)||this.textures.has(t)||this.externalTextures.has(t);)t=`${e}-${n++}`;return t}createDataView(e,t){this.assertBuffer(e);let n=I(t.format),o=t.byteOffset??0,i=t.rowByteLength??n.byteLength,s=t.byteStride??i;return au(e,{length:t.length,byteOffset:o,byteStride:s,rowByteLength:i}),new Ge(e,{format:t.format,length:t.length,byteOffset:o,byteStride:s,rowByteLength:i})}importGPUData(e,t){return this.importGPUDataView(e,t)}importGPUVector(e,t){if(t.bufferLayout)throw new Error(`GPUCommandGraph import "${e}" does not accept interleaved GPUVector data`);let n=t.format??t.data[0]?.format;if(!n)throw new Error(`GPUCommandGraph import "${e}" requires GPUVector.format`);if(et(n)||tt(n))throw new Error(`GPUCommandGraph import "${e}" requires a fixed-width GPUVector format`);let o=I(n),i=t.data.map((s,a)=>{if(s.format!==n)throw new Error(`GPUCommandGraph import "${e}" requires matching GPUVector chunk formats`);let u=t.data.length===1?e:`${e}-chunk-${a}`;return this.importGPUDataView(u,s)});return new G({id:e,name:t.name??e,format:n,length:t.length,valueLength:t.valueLength??t.data.reduce((s,a)=>s+a.valueLength,0),stride:t.stride??t.data[0]?.stride??o.components*(o.listSize??1),byteStride:t.byteStride??i[0]?.byteStride??o.byteLength,rowByteLength:t.rowByteLength??i[0]?.rowByteLength??o.byteLength,data:i})}importTexture(e,t){this.assertMutable();let n=eo(e,this.device);return t&&no(t,n,this.device),this.addTexture(new Se(this,n,!1,t))}importFrameTexture(e){this.assertMutable();let t=eo(e,this.device);return this.addTexture(new Se(this,t,!1,void 0,!0))}importExternalTexture(e){return this.assertMutable(),iu(e,this.device),this.addExternalTexture(new ot(this,e))}createTransientTexture(e){this.assertMutable();let t=eo(e,this.device);return this.addTexture(new Se(this,t,!0))}createTextureView(e,t={}){this.assertTexture(e);let n=su(e,t);return new De(e,n)}add(e){if(this.assertMutable(),"getNodes"in e)for(let t of e.getNodes())this.add(t);else if("getCommandNodes"in e)Me(this,e.getCommandNodes(this));else if("type"in e)Jn(this,e);else for(let t of e)this.add(t)}addComputePass(e){this.addNode({...e,type:"compute"})}addRenderPass(e){e.attachments&&this.validateRenderAttachments(e.id,e.attachments);let t=e.attachments?[...e.attachments.colorAttachments.map(n=>({texture:n,usage:"render-attachment"})),...(e.attachments.resolveTargets??[]).filter(n=>n!==null).map(n=>({texture:n,usage:"render-attachment"})),...e.attachments.depthStencilAttachment?[{texture:e.attachments.depthStencilAttachment,usage:"render-attachment"}]:[]]:[];this.addNode({...e,resources:[...e.resources??[],...t],type:"render"})}addCopyPass(e){this.addNode({...e,type:"copy"})}compile(){return this.assertMutable(),Fr(this.device,"compilation"),this.compiled=!0,new ht(Ci({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}async compileAsync(){return this.assertMutable(),Fr(this.device,"compilation"),this.compiled=!0,new ht(await Li({device:this.device,id:this.id,buffers:this.buffers,textures:this.textures,externalTextures:this.externalTextures,nodes:this.nodes}))}addNode(e){if(this.device.type!=="webgpu"&&e.type!=="render")throw new Error("WebGL graphs support render passes only");if(this.assertMutable(),!e.id)throw new Error("GPUCommandGraph node id is required");if(this.nodeIds.has(e.id))throw new Error(`GPUCommandGraph node id "${e.id}" is already in use`);for(let[t,n]of Object.entries(e.workload??{}))if(t==="operation"||t==="variant"){if(typeof n!="string"||!n)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be nonempty`)}else if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error(`GPUCommandGraph node "${e.id}" workload ${t} must be a nonnegative safe integer`);if(e.condition){if(!e.condition.id)throw new Error(`GPUCommandGraph node "${e.id}" condition id is required`);if(e.condition.source==="cpu"){if(typeof e.condition.evaluate!="function")throw new Error(`GPUCommandGraph node "${e.id}" CPU condition requires an evaluate function`)}else{let t=e.condition;if(e.type!=="compute"||t.mode!=="indirect")throw new Error(`GPUCommandGraph node "${e.id}" GPU conditions require an indirect compute node`);if(!t.buffer)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition requires an indirect command buffer`);this.assertBuffer(t.buffer);let n=t.byteOffset??0;if(!Number.isSafeInteger(n)||n<0||n%4!==0)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition byteOffset must be a nonnegative multiple of 4`);if(n+3*Ja>t.buffer.byteLength)throw new Error(`GPUCommandGraph node "${e.id}" GPU condition indirect command exceeds buffer "${t.buffer.id}"`);(e.resources??[]).some(o=>nt(o)&&ve(o.buffer)===t.buffer&&o.usage==="indirect")||(e={...e,resources:[...e.resources??[],{buffer:t.buffer,usage:"indirect"}]})}}if(e.publication){if(e.condition)throw new Error(`GPUCommandGraph node "${e.id}" cannot combine conditional execution with a publication boundary`);if(!e.publication.id)throw new Error(`GPUCommandGraph node "${e.id}" publication id is required`);if(!["partial","complete"].includes(e.publication.completeness))throw new Error(`GPUCommandGraph node "${e.id}" publication completeness is invalid`)}for(let t of e.resources??[])if(nt(t)){let n=ve(t.buffer);this.assertBuffer(n),cu(n,t.usage)}else if(ir(t)){let n=Fe(t.texture);if(this.assertTexture(n),du(n,t.usage),fu(t.texture,t.usage),this.device.type==="webgl"&&t.usage==="sampled"&&t.texture instanceof De&&!Vi(t.texture))throw new Error("WebGL sampled textures require a full-resource view")}else{if(this.assertExternalTexture(t.externalTexture),t.usage!=="sampled")throw new Error("GPUCommandGraph external textures support sampled access only");if(e.type!=="render")throw new Error("GPUCommandGraph external textures can be sampled only by render nodes")}Oi(e),this.nodeIds.add(e.id),this.nodes.push(e)}addBuffer(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.buffers.set(e.id,e),e}addTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.textures.set(e.id,e),e}addExternalTexture(e){if(this.buffers.has(e.id)||this.textures.has(e.id)||this.externalTextures.has(e.id))throw new Error(`GPUCommandGraph resource id "${e.id}" is already in use`);return this.externalTextures.set(e.id,e),e}importGPUDataView(e,t){if(!t.format)throw new Error(`GPUCommandGraph import "${e}" requires GPUData.format`);let n=ur(t.buffer),o={byteLength:ru(t),usage:n.usage},i=t.buffer instanceof we?this.getDynamicBufferHandle(t.buffer,o):this.getImportedBufferHandle(n,o);return i||(i=this.importBuffer({id:e,byteLength:n.byteLength,usage:n.usage},t.buffer),t.buffer instanceof we?this.dynamicBufferHandles.set(t.buffer,i):this.importedBufferHandles.set(n,i)),this.createDataView(i,{format:t.format,length:t.length,byteOffset:t.byteOffset,byteStride:t.byteStride,rowByteLength:t.rowByteLength})}getDynamicBufferHandle(e,t){let n=this.dynamicBufferHandles.get(e);if(n?.defaultBuffer===e&&sr(n,t))return n;this.dynamicBufferHandles.delete(e);for(let o of this.buffers.values())if(o.defaultBuffer===e&&sr(o,t))return this.dynamicBufferHandles.set(e,o),o}getImportedBufferHandle(e,t){let n=this.importedBufferHandles.get(e);if(n?.defaultBuffer&&ur(n.defaultBuffer)===e&&sr(n,t))return n;this.importedBufferHandles.delete(e);for(let[o,i]of this.dynamicBufferHandles)if(o.buffer===e&&sr(i,t))return this.importedBufferHandles.set(e,i),i;for(let o of this.buffers.values())if(o.defaultBuffer===e&&sr(o,t))return this.importedBufferHandles.set(e,o),o}assertBuffer(e){if(e.graph!==this||this.buffers.get(e.id)!==e)throw new Error(`Graph buffer "${e.id}" does not belong to ${this.id}`)}assertTexture(e){if(e.graph!==this||this.textures.get(e.id)!==e)throw new Error(`Graph texture "${e.id}" does not belong to ${this.id}`)}assertExternalTexture(e){if(e.graph!==this||this.externalTextures.get(e.id)!==e)throw new Error(`Graph external texture "${e.id}" does not belong to ${this.id}`)}assertMutable(){if(this.compiled)throw new Error(`GPUCommandGraph "${this.id}" has already been compiled`)}validateRenderAttachments(e,t){if(t.colorAttachments.length===0&&!t.depthStencilAttachment)throw new Error(`GPUCommandGraph render node "${e}" requires at least one attachment`);let n=[...t.colorAttachments,...t.depthStencilAttachment?[t.depthStencilAttachment]:[]];for(let s of n)if(this.assertTexture(s.texture),s.dimension!=="2d"||s.mipLevelCount!==1||s.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" attachments must be single-mip, single-layer 2d views`);let[o,...i]=n;for(let s of i)if(s.width!==o.width||s.height!==o.height||s.texture.samples!==o.texture.samples)throw new Error(`GPUCommandGraph render node "${e}" attachments must have matching extent and samples`);this.validateResolveTargets(e,t)}validateResolveTargets(e,t){let n=t.resolveTargets;if(n){if(this.device.type!=="webgpu")throw new Error(`GPUCommandGraph render node "${e}" resolve targets require WebGPU`);if(n.length!==t.colorAttachments.length)throw new Error(`GPUCommandGraph render node "${e}" requires one resolve entry per color attachment`);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let s=t.colorAttachments[o];if(this.assertTexture(i.texture),s.texture.samples<=1||i.texture.samples!==1||s.format!==i.format||s.width!==i.width||s.height!==i.height)throw new Error(`GPUCommandGraph render node "${e}" resolve target ${o} must match a multisampled source and be single-sampled`);if(i.dimension!=="2d"||i.aspect!=="all"||i.mipLevelCount!==1||i.arrayLayerCount!==1)throw new Error(`GPUCommandGraph render node "${e}" resolve targets must be single-mip, single-layer 2d color views`)}}}},ht=class{device;id;stats;preflight;capabilities;buffers;textures;externalTextures;compiledNodes;activeImportedBufferHandles=new Set;writableImportedBufferHandles=new Set;activeImportedTextureHandles=new Set;writableImportedTextureHandles=new Set;transientBuffers;transientTextures;bufferTransientAllocations;textureTransientAllocations;cachedTextureViews=[];cachedFramebuffers=[];lastFrameIds=new Map;lastExternalTextureFrameIds=new Map;consumedExternalTextures=new WeakSet;destroyed=!1;get[Symbol.toStringTag](){return"CompiledGPUCommandGraph"}toString(){let e=this.destroyed?"destroyed":"active";return`${this[Symbol.toStringTag]}:"${this.id}":${this.stats.nodeOrder.length} nodes:${this.stats.physicalTransientResourceBytes}B transient:${e}`}toJSON(){return this.toString()}constructor(e){this.device=e.device,this.id=e.id,this.buffers=e.buffers,this.textures=e.textures,this.externalTextures=e.externalTextures,this.compiledNodes=e.compiledNodes;for(let{node:t}of this.compiledNodes)for(let n of t.resources??[])if(nt(n)){let o=ve(n.buffer);o.transient||(this.activeImportedBufferHandles.add(o),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="copy-destination")&&this.writableImportedBufferHandles.add(o))}else if(ir(n)){let o=Fe(n.texture);o.transient||(this.activeImportedTextureHandles.add(o),(n.usage==="storage-write"||n.usage==="storage-read-write"||n.usage==="render-attachment"||n.usage==="copy-destination")&&this.writableImportedTextureHandles.add(o))}this.transientBuffers=e.transientBuffers,this.transientTextures=e.transientTextures,this.bufferTransientAllocations=e.bufferTransientAllocations,this.textureTransientAllocations=e.textureTransientAllocations,this.stats=e.stats,this.preflight=e.preflight,this.capabilities=ou(this.device)}encode(e,t){return this.encodeNodeRange(e,t,0,this.compiledNodes.length)}getExecutionPlan(e,t={}){return Rr(this.preflight,e,t)}createExecution(e,t={}){return new It({plan:this.getExecutionPlan(e,t),budget:e,encodeNodeRange:(n,o,i,s)=>this.encodeNodeRange(n,o,i,s)})}encodeNodeRange(e,t,n,o){if(this.destroyed)throw new Error(`CompiledGPUCommandGraph "${this.id}" has been destroyed`);if(Fr(this.device,"encoding"),e.device!==this.device)throw new Error("GPUCommandGraph command encoder must belong to the graph device");let i=ar(),s=this.resolveImportedBuffers(t.buffers??{});nu(t.frameTextures??{},t.externalTextures??{});let a=this.resolveImportedTextures(t.textures??{},t.frameTextures??{}),u=this.resolveExternalTextures(t.externalTextures??{});for(let[T,b]of a.frameIds)this.lastFrameIds.set(T,b);for(let[T,b]of u.frameIds)this.lastExternalTextureFrameIds.set(T,b);for(let T of u.textures.values())this.consumedExternalTextures.add(T);let c=a.textures,d=T=>{let b=ve(T),P=b.transient?this.transientBuffers.get(b):s.get(b);if(!P)throw new Error(`GPUCommandGraph buffer "${b.id}" is not bound`);return P},f=T=>{let b=Fe(T),P=b.transient?this.transientTextures.get(b):c.get(b);if(!P)throw new Error(`GPUCommandGraph texture "${b.id}" is not bound`);return P},l=T=>{let b=f(T);if(T instanceof Se||Vi(T))return b.view;if(T.texture.frameScoped){let E=this.lastFrameIds.get(T.texture);for(let O=this.cachedTextureViews.length-1;O>=0;O--){let C=this.cachedTextureViews[O];C.logicalView===T&&C.frameId!==E&&(this.destroyFramebuffersUsingView(C.view),C.view.destroy(),this.cachedTextureViews.splice(O,1))}}let P=this.cachedTextureViews.find(E=>E.logicalView===T&&E.texture===b&&(!T.texture.frameScoped||E.frameId===this.lastFrameIds.get(T.texture)));if(P)return P.view;let B=b.createView({format:T.format,dimension:T.dimension,aspect:T.aspect,baseMipLevel:T.baseMipLevel,mipLevelCount:T.mipLevelCount,baseArrayLayer:T.baseArrayLayer,arrayLayerCount:T.arrayLayerCount});return this.cachedTextureViews.push({logicalView:T,texture:b,view:B,...T.texture.frameScoped?{frameId:this.lastFrameIds.get(T.texture)}:{}}),B},h=T=>{let b=u.textures.get(T);if(!b)throw new Error(`GPUCommandGraph external texture "${T.id}" is not bound`);return b},m={commandEncoder:e,parameters:t.parameters,getBuffer:d,getTexture:f,getTextureView:l,getExternalTexture:h},g=[],y,p=0,w=t.coalesceComputePasses!==!1&&e.getTimeProfilingQuerySet()===null,S=()=>{let T=y;y=void 0,T?.end()};try{for(let T=n;T<o;T++){let{node:b,executable:P}=this.compiledNodes[T],B=ar();if(b.condition?.source==="cpu"){let C=!1;try{C=b.condition.evaluate(t.parameters)}catch(U){let M=U instanceof Error?U.message:String(U);throw new Error(`GPUCommandGraph CPU condition "${b.condition.id}" failed for node "${b.id}": ${M}`)}if(!C){let U=ar();g.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[T].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:U,cpuEncodeTimeMilliseconds:U-B,hasGPUTimestamps:!1,condition:{id:b.condition.id,source:"cpu",outcome:"skipped"}}});continue}}let E;switch(b.type){case"compute":{y||(y=e.beginComputePass({id:b.id}),p++);let C=y;E=_i(C,e),E&&(w=!1),C.pushDebugGroup(b.id);try{let U=b.condition?.source==="gpu"?b.condition:void 0,M=U?tu(C,d(U.buffer),U.byteOffset??0,b.id):void 0;P.encode({...m,computePass:M?.computePass??C}),M?.assertDispatched()}finally{C.popDebugGroup()}w||S();break}case"render":{S();let C=P,U=C.getRenderPassProps?.(m)??{id:b.id};if(b.attachments&&U.framebuffer!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply framebuffer with graph attachments`);if(b.attachments?.resolveTargets&&U.resolveTargets!==void 0)throw new Error(`GPUCommandGraph render node "${b.id}" cannot supply resolveTargets with graph attachments`);let M=b.attachments?this.getFramebuffer(b.id,b.attachments,l):void 0,V=b.attachments?.resolveTargets?.map(te=>te?l(te):null),de=e.beginRenderPass({...U,...M?{framebuffer:M}:{},...V?{resolveTargets:V}:{}});E=_i(de,e),de.pushDebugGroup(b.id);try{C.encode({...m,renderPass:de})}finally{de.popDebugGroup(),de.end()}break}case"copy":S(),P.encode(m);break}let O=ar();g.push({stats:{id:b.id,description:b.description,resources:this.preflight.nodes[T].resources,operation:b.workload?.operation,type:b.type,cpuEncodeStartTimeMilliseconds:B,cpuEncodeEndTimeMilliseconds:O,cpuEncodeTimeMilliseconds:O-B,hasGPUTimestamps:E!==void 0,...b.condition?{condition:{id:b.condition.id,source:b.condition.source,outcome:b.condition.source==="gpu"?"gpu-resolved":"executed"}}:{}},timestamp:E})}}finally{S()}let v=ar();return new Ut(g,v-i,p,i,v,async(T,b)=>{if(this.destroyed)throw new Error("Graph has been destroyed.");let P=this.compiledNodes.findIndex(({node:M})=>M.id===T),B=this.compiledNodes[P]?.node.resources?.[b],E=this.preflight.nodes[P]?.resources?.[b];if(!B||!E)throw new Error("Resource is unavailable.");if("externalTexture"in B)throw new Error("External images cannot be read back.");let O="buffer"in B?ve(B.buffer):Fe(B.texture);if("frameScoped"in O&&O.frameScoped)throw new Error("Frame textures expire after presentation.");let C="buffer"in B?d(B.buffer):f(B.texture),U=C instanceof se.Buffer?this.transientBuffers:this.transientTextures;if(O.transient&&[...U].some(([M,V])=>M!==O&&V===C))throw new Error("Transient allocation is reused; logical contents are no longer available.");return Ro(C,E)})}destroy(){if(!this.destroyed){for(let{executable:e}of this.compiledNodes)e.destroy?.();for(let e of this.cachedFramebuffers)e.framebuffer.destroy();for(let e of this.cachedTextureViews)e.view.destroy();for(let e of this.bufferTransientAllocations)e.buffer?.destroy();for(let e of this.textureTransientAllocations)e.texture?.destroy();this.destroyed=!0}}resolveImportedBuffers(e){let t=new Map,n=new Map;for(let[o,i]of this.buffers){if(i.transient)continue;let s=e[o]??i.defaultBuffer;if(!s)throw new Error(`GPUCommandGraph imported buffer "${o}" is required`);Mi(s,i,this.device);let a=ur(s);if(this.activeImportedBufferHandles.has(i)){let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,d=n.get(c);if(d&&(this.writableImportedBufferHandles.has(d)||this.writableImportedBufferHandles.has(i)))throw new Error(`GPUCommandGraph imported buffers "${d.id}" and "${o}" resolve to the same physical buffer`);d||n.set(c,i)}t.set(i,a)}for(let o of Object.keys(e)){let i=this.buffers.get(o);if(!i||i.transient)throw new Error(`GPUCommandGraph has no imported buffer named "${o}"`)}return t}resolveImportedTextures(e,t){let n=new Map,o=new Map;for(let[s,a]of this.textures){if(a.transient)continue;if(a.frameScoped){let c=t[s];if(!c)throw new Error(`GPUCommandGraph frame texture "${s}" is required`);let d=this.lastFrameIds.get(a);if(d!==void 0&&c.frameId<=d)throw new Error(`GPUCommandGraph frame texture "${s}" frameId ${c.frameId} is stale; expected greater than ${d}`);no(c.texture,a,this.device),n.set(a,ro(c.texture)),o.set(a,c.frameId);continue}let u=e[s]??a.defaultTexture;if(!u)throw new Error(`GPUCommandGraph imported texture "${s}" is required`);no(u,a,this.device),n.set(a,ro(u))}for(let s of Object.keys(e)){let a=this.textures.get(s);if(!a||a.transient||a.frameScoped)throw new Error(`GPUCommandGraph has no imported texture named "${s}"`)}for(let s of Object.keys(t))if(!this.textures.get(s)?.frameScoped)throw new Error(`GPUCommandGraph has no frame texture named "${s}"`);let i=new Map;for(let[s,a]of n){if(!this.activeImportedTextureHandles.has(s))continue;let u=a.handle,c=typeof u=="object"&&u!==null||typeof u=="function"?u:a,d=i.get(c);if(d&&(this.writableImportedTextureHandles.has(d)||this.writableImportedTextureHandles.has(s)))throw new Error(`GPUCommandGraph imported textures "${d.id}" and "${s.id}" resolve to the same physical texture`);d||i.set(c,s)}return{textures:n,frameIds:o}}resolveExternalTextures(e){let t=new Map,n=new Map;for(let[o,i]of this.externalTextures){let s=e[o];if(!s)throw new Error(`GPUCommandGraph external texture "${o}" is required`);let a=this.lastExternalTextureFrameIds.get(i);if(a!==void 0&&s.frameId<=a)throw new Error(`GPUCommandGraph external texture "${o}" frameId ${s.frameId} is stale; expected greater than ${a}`);if(this.consumedExternalTextures.has(s.texture))throw new Error(`GPUCommandGraph external texture "${o}" requires a fresh binding for each frame`);uu(s.texture,i,this.device),t.set(i,s.texture),n.set(i,s.frameId)}for(let o of Object.keys(e))if(!this.externalTextures.has(o))throw new Error(`GPUCommandGraph has no external texture named "${o}"`);return{textures:t,frameIds:n}}getFramebuffer(e,t,n){let o=t.colorAttachments.map(n),i=t.depthStencilAttachment?n(t.depthStencilAttachment):void 0,s=this.cachedFramebuffers.find(c=>c.nodeId===e&&c.depthStencilAttachment===i&&c.colorAttachments.length===o.length&&c.colorAttachments.every((d,f)=>d===o[f]));if(s)return s.framebuffer;let a=t.colorAttachments[0]??t.depthStencilAttachment,u=this.device.createFramebuffer({id:`${this.id}-${e}-framebuffer-${this.cachedFramebuffers.length}`,width:a.width,height:a.height,colorAttachments:o,depthStencilAttachment:i??null});return this.cachedFramebuffers.push({nodeId:e,colorAttachments:o,depthStencilAttachment:i,framebuffer:u}),u}destroyFramebuffersUsingView(e){for(let t=this.cachedFramebuffers.length-1;t>=0;t--){let n=this.cachedFramebuffers[t];(n.depthStencilAttachment===e||n.colorAttachments.some(o=>o===e))&&(n.framebuffer.destroy(),this.cachedFramebuffers.splice(t,1))}}};function ur(r){return r instanceof we?r.buffer:r}function ru(r){let e=r.length===0?0:(r.length-1)*r.byteStride+r.rowByteLength;return r.byteOffset+e}function sr(r,e){return r.byteLength>=e.byteLength&&(r.usage&e.usage)===e.usage}function ro(r){if(r instanceof Je){if(!r.isReady)throw new Error(`GPUCommandGraph dynamic texture "${r.id}" is not ready`);return r.texture}return r}function nu(r,e){let t;for(let[n,o]of[...Object.entries(r),...Object.entries(e)]){if(!Number.isSafeInteger(o.frameId)||o.frameId<0)throw new Error(`GPUCommandGraph frame resource "${n}" requires a valid frameId`);if(t!==void 0&&o.frameId!==t)throw new Error("GPUCommandGraph frame resources must share one frameId per encoding");t=o.frameId}}function _i(r,e){let{timestampQuerySet:t,beginTimestampIndex:n,endTimestampIndex:o}=r.props;return t&&Number.isSafeInteger(n)&&Number.isSafeInteger(o)&&n>=0&&o>n?{querySet:t,snapshot:t.device.type==="webgpu"?e.captureTimestampQuerySet?.(t):void 0,beginIndex:n,endIndex:o}:void 0}function ou(r){return Object.freeze({timestampQueries:r.features.has("timestamp-query"),subgroups:r.features.has("subgroups"),subgroupId:r.wgslLanguageFeatures.has("subgroup_id"),subgroupMinSize:r.info.subgroupMinSize,subgroupMaxSize:r.info.subgroupMaxSize,softwareAdapter:r.info.gpu==="software"||r.info.gpuType==="cpu"||!!r.info.fallback,maxBufferByteLength:r.limits.maxBufferSize,maxStorageBufferBindingByteLength:r.limits.maxStorageBufferBindingSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension})}function Fr(r,e){if(r.isLost)throw new Error(`GPUCommandGraph cannot perform ${e} after device loss`)}function ar(){return globalThis.performance?.now()??Date.now()}function Fi(r,e){if(!r.id)throw new Error("GPUCommandGraph buffer id is required");if(!Number.isSafeInteger(r.byteLength)||r.byteLength<0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires a valid byteLength`);if(r.byteLength>e.limits.maxBufferSize)throw new Error(`GPUCommandGraph buffer "${r.id}" exceeds the device buffer limit`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph buffer "${r.id}" requires buffer usage flags`)}function iu(r,e){if(!r.id)throw new Error("GPUCommandGraph external texture id is required");for(let[t,n]of Object.entries({width:r.width,height:r.height}))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`GPUCommandGraph external texture "${r.id}" ${t} must be a positive safe integer`);if(r.width>e.limits.maxTextureDimension2D||r.height>e.limits.maxTextureDimension2D)throw new Error(`GPUCommandGraph external texture "${r.id}" exceeds device dimension limits`)}function eo(r,e){if(!r.id)throw new Error("GPUCommandGraph texture id is required");let t=r.dimension??"2d",n=t==="cube"?6:r.depth??1,o=r.mipLevels??1,i=r.samples??1;for(let[c,d]of Object.entries({width:r.width,height:r.height,depth:n,mipLevels:o,samples:i}))if(!Number.isSafeInteger(d)||d<=0)throw new Error(`GPUCommandGraph texture "${r.id}" ${c} must be a positive safe integer`);if(!Number.isSafeInteger(r.usage)||r.usage<=0)throw new Error(`GPUCommandGraph texture "${r.id}" requires texture usage flags`);if(!e.isTextureFormatSupported(r.format))throw new Error(`GPUCommandGraph texture "${r.id}" format ${r.format} is unsupported`);if(t==="1d"&&(r.height!==1||n!==1))throw new Error(`GPUCommandGraph 1d texture "${r.id}" requires height and depth 1`);if(t==="cube"&&r.width!==r.height)throw new Error(`GPUCommandGraph cube texture "${r.id}" must be square`);if(t==="cube-array"&&(r.width!==r.height||n%6!==0))throw new Error(`GPUCommandGraph cube-array texture "${r.id}" must be square with depth divisible by 6`);if(o>e.getMipLevelCount(r.width,r.height,t==="3d"?n:1))throw new Error(`GPUCommandGraph texture "${r.id}" declares too many mip levels`);let s=t==="1d"?e.limits.maxTextureDimension1D:t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,a=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureDimension2D,u=t==="3d"?e.limits.maxTextureDimension3D:e.limits.maxTextureArrayLayers;if(r.width>s||r.height>a||n>u)throw new Error(`GPUCommandGraph texture "${r.id}" exceeds device dimension limits`);return{id:r.id,format:r.format,width:r.width,height:r.height,usage:r.usage,dimension:t,depth:n,mipLevels:o,samples:i}}function su(r,e){let t=e.dimension??r.dimension,n=e.aspect??"all",o=e.baseMipLevel??0,i=e.mipLevelCount??r.mipLevels-o,s=e.baseArrayLayer??0,a=r.dimension==="3d"?1:r.depth,u=e.arrayLayerCount??a-s;for(let[l,h]of Object.entries({baseMipLevel:o,mipLevelCount:i,baseArrayLayer:s,arrayLayerCount:u}))if(!Number.isSafeInteger(h)||h<0)throw new Error(`Graph texture view ${l} must be a non-negative safe integer`);if(i===0||o+i>r.mipLevels)throw new Error(`Graph texture view exceeds texture "${r.id}" mip levels`);if(u===0||s+u>a||r.dimension==="3d"&&(s!==0||u!==1))throw new Error(`Graph texture view exceeds texture "${r.id}" array layers`);let c=Math.max(1,r.width>>o),d=r.dimension==="1d"?1:Math.max(1,r.height>>o),f=r.dimension==="3d"?Math.max(1,r.depth>>o):u;return{dimension:t,aspect:n,baseMipLevel:o,mipLevelCount:i,baseArrayLayer:s,arrayLayerCount:u,width:c,height:d,depth:f}}function au(r,e){for(let[o,i]of Object.entries(e))if(!Number.isSafeInteger(i)||i<0)throw new Error(`Graph data view ${o} must be a non-negative safe integer`);if(e.length>1&&e.byteStride===0)throw new Error("Graph data view byteStride must be positive for multiple rows");if(e.rowByteLength>e.byteStride&&e.length>1)throw new Error("Graph data view rowByteLength cannot exceed byteStride");let t=e.length===0?0:(e.length-1)*e.byteStride+e.rowByteLength,n=e.byteOffset+t;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n))throw new Error("Graph data view byte range exceeds safe integer precision");if(n>r.byteLength)throw new Error(`Graph data view exceeds buffer "${r.id}" byte length`)}function Mi(r,e,t){let n=ur(r);if(n.device!==t)throw new Error(`GPUCommandGraph buffer "${e.id}" belongs to another device`);if(n.byteLength<e.byteLength)throw new Error(`GPUCommandGraph buffer "${e.id}" is smaller than compiled capacity`);if((n.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph buffer "${e.id}" has incompatible usage flags`)}function no(r,e,t){let n=ro(r);if(n.device!==t)throw new Error(`GPUCommandGraph texture "${e.id}" belongs to another device`);for(let[o,i,s]of[["format",e.format,n.format],["dimension",e.dimension,n.dimension],["width",e.width,n.width],["height",e.height,n.height],["depth",e.depth,n.depth],["mipLevels",e.mipLevels,n.mipLevels],["samples",e.samples,n.samples]])if(s!==i)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible ${o} (${s} !== ${i})`);if((n.props.usage&e.usage)!==e.usage)throw new Error(`GPUCommandGraph texture "${e.id}" has incompatible usage flags`)}function uu(r,e,t){if(r.device!==t)throw new Error(`GPUCommandGraph external texture "${e.id}" belongs to another device`);if(r.destroyed)throw new Error(`GPUCommandGraph external texture "${e.id}" has been destroyed`);if(r.width!==e.width||r.height!==e.height)throw new Error(`GPUCommandGraph external texture "${e.id}" has incompatible dimensions (${r.width}x${r.height} !== ${e.width}x${e.height})`)}function cu(r,e){let t=lu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph buffer "${r.id}" does not declare usage required by ${e}`)}function du(r,e){let t=hu(e);if((r.usage&t)!==t)throw new Error(`GPUCommandGraph texture "${r.id}" does not declare usage required by ${e}`)}function fu(r,e){if(r instanceof De&&e.startsWith("storage-")&&r.mipLevelCount!==1)throw new Error("GPUCommandGraph storage texture views must contain exactly one mip level")}function lu(r){switch(r){case"storage-read":case"storage-write":case"storage-read-write":return se.Buffer.STORAGE;case"uniform":return se.Buffer.UNIFORM;case"copy-source":return se.Buffer.COPY_SRC;case"copy-destination":return se.Buffer.COPY_DST;case"indirect":return se.Buffer.INDIRECT;case"vertex":return se.Buffer.VERTEX;case"index":return se.Buffer.INDEX}}function hu(r){switch(r){case"sampled":return se.Texture.SAMPLE;case"storage-read":case"storage-write":case"storage-read-write":return se.Texture.STORAGE;case"render-attachment":return se.Texture.RENDER;case"copy-source":return se.Texture.COPY_SRC;case"copy-destination":return se.Texture.COPY_DST}}function Vi(r){let e=r.texture;return r.dimension===e.dimension&&r.aspect==="all"&&r.baseMipLevel===0&&r.mipLevelCount===e.mipLevels&&r.baseArrayLayer===0&&r.arrayLayerCount===(e.dimension==="3d"?1:e.depth)}var mt=class extends to{constructor(e,t={}){if(e.type!=="webgpu")throw new Error("GPUCommandGraph requires a WebGPU device");super(e,t)}};var vt=R(A(),1);var D=R(A(),1);var N={texture(r){return Object.freeze({...r,type:"texture",...r.extent?{extent:Object.freeze({...r.extent,..."scale"in r.extent&&r.extent.scale?{scale:Object.freeze([...r.extent.scale])}:{}})}:{}})},scalar(r){return Object.freeze({type:"scalar",format:r})},vector(r,e={}){return Object.freeze({type:"vector",format:r,...e,...e.chunkLengths?{chunkLengths:Object.freeze([...e.chunkLengths])}:{}})}},Ie=class{role;id;format;constructor(e,t,n){if(this.role=n,!e)throw new Error("GPUGraphScalar id is required");this.id=e,this.format=t}},K=class{id;format;length;external;role;chunkLengths;constructor(e){if(!e.id)throw new Error("GPUGraphVector id is required");if(e.length!==void 0&&(!Number.isSafeInteger(e.length)||e.length<0))throw new Error(`${e.id} vector length must be a non-negative safe integer`);if(this.id=e.id,this.format=e.format,this.length=e.length,this.external=e.external??!1,this.role=e.role,e.chunkLengths){if(e.chunkLengths.some(t=>!Number.isSafeInteger(t)||t<0)||e.length!==void 0&&e.chunkLengths.reduce((t,n)=>t+n,0)!==e.length)throw new Error(`${e.id} chunk lengths must partition its logical length`);this.chunkLengths=Object.freeze([...e.chunkLengths])}}},ae=class{id;format;width;height;role;descriptor;usage;dimension;depth;mipLevels;samples;external;constructor(e){this.role=e.role,this.descriptor=e.descriptor?N.texture(e.descriptor):void 0,this.id=e.id,this.format=e.format,this.width=e.width,this.height=e.height,this.usage=e.usage,this.dimension=e.dimension,this.depth=e.depth,this.mipLevels=e.mipLevels,this.samples=e.samples,this.external=e.external??!1}},Ue=class{texture;props;constructor(e,t={}){this.texture=e,this.props=Object.freeze({...t})}};function k(r){return typeof r=="string"?r:r.id}function oo(r,e){let t=k(e),n=[...r.scalars,...r.vectors,...r.textures].find(o=>o.id===t);if(!n)throw new Error(`Undeclared operation value ${t}`);if(typeof e!="string"&&(e.constructor!==n.constructor||e.format!==n.format))throw new Error(`Incompatible operation reference ${t}`);return n}function $t(r,e){for(let t of e.values){let n=oo(r,t.value);if(n instanceof ae&&t.shape&&"like"in t.shape){if(!(oo(r,t.shape.like)instanceof ae))throw new Error("Texture shape requires a texture source");continue}if(t.shape){if(!(n instanceof K)||t.access==="read")throw new Error("Operation shapes require writable vectors");if("like"in t.shape){if(!(oo(r,t.shape.like)instanceof K))throw new Error("Operation shape source must be a vector");let o=k(t.shape.like);if(!e.values.some(i=>i.access!=="write"&&k(i.value)===o))throw new Error("Operation shape source must be a declared read")}else{let{length:o,chunkLengths:i}=t.shape;if(!Number.isSafeInteger(o)||o<0||i&&(i.some(s=>!Number.isSafeInteger(s)||s<0)||i.reduce((s,a)=>s+a,0)!==o))throw new Error("Invalid operation output shape")}}}}function Q(r){let e=r instanceof D.TextureView?r.texture:r,t=r instanceof D.TextureView?r.props:{},n=t.baseMipLevel??0,o=t.baseArrayLayer??0,i=t.dimension??e.dimension,s=t.mipLevelCount??e.mipLevels-n,a=i==="3d"?Math.max(1,e.depth>>n):t.arrayLayerCount??(i==="cube"?6:i==="2d"?1:e.depth-o);return(0,D.assert)((t.format??e.format)===e.format&&(t.aspect??"all")==="all"),(0,D.assert)(!r.destroyed&&!e.destroyed),(0,D.assert)(Number.isInteger(n)&&n>=0&&Number.isInteger(s)&&s>0&&n+s<=e.mipLevels),(0,D.assert)(Number.isInteger(o)&&o>=0&&Number.isInteger(a)&&a>0&&(i==="3d"?o===0:o+a<=e.depth)),{texture:e,format:e.format,dimension:i,width:Math.max(1,e.width>>n),height:Math.max(1,e.height>>n),depth:a,mipLevels:s,samples:e.samples,baseMipLevel:n,baseArrayLayer:o}}function Ni(r,e={}){let t=Q(r),n=e.baseMipLevel??0,o=e.baseArrayLayer??0,i=e.dimension??t.dimension,s=e.mipLevelCount??t.mipLevels-n,a=e.arrayLayerCount??(i==="cube"?6:i==="2d"||i==="3d"?1:t.depth-o);return(0,D.assert)(n>=0&&n+s<=t.mipLevels&&o>=0&&o+a<=t.depth),{...e,dimension:i,baseMipLevel:t.baseMipLevel+n,mipLevelCount:s,baseArrayLayer:t.baseArrayLayer+o,arrayLayerCount:a}}var mu={sampled:D.Texture.SAMPLE,"storage-read":D.Texture.STORAGE,"storage-write":D.Texture.STORAGE,"storage-read-write":D.Texture.STORAGE,"render-attachment":D.Texture.RENDER,"copy-source":D.Texture.COPY_SRC,"copy-destination":D.Texture.COPY_DST},Mr=class{values=new Map;owned=new Set;constructor(e,t,n,o,i){let s=new Map,a=new Set;for(let u of n)for(let c of u.values){let d=k(c.value);if(!t.some(l=>l.id===d))continue;(0,D.assert)(c.textureUsage);let f=c.textureUsage;(0,D.assert)(c.access==="read"&&["sampled","storage-read","copy-source"].includes(f)||c.access==="write"&&["storage-write","render-attachment","copy-destination"].includes(f)||c.access==="read-write"&&["storage-read-write","render-attachment"].includes(f)),s.set(d,(s.get(d)??0)|mu[f]),c.access!=="read"&&a.add(d)}try{let u=new Set(t);for(;u.size;){let c=!1;for(let d of u){let f=d.descriptor??{type:"texture",format:d.format,dimension:d.dimension,extent:d.width===void 0?void 0:{width:d.width,height:d.height,depth:d.depth},mipLevels:d.mipLevels,samples:d.samples},l=f.extent,h=l&&"like"in l?this.values.get(l.like):void 0;if(l&&"like"in l&&!h)continue;let m=h?Q(h):void 0,g=l&&"like"in l?l.scale??[1,1]:[1,1];(0,D.assert)(g.every(E=>Number.isFinite(E)&&E>0));let y=m?Math.max(1,Math.round(m.width*g[0])):l&&"width"in l?l.width:void 0,p=m?Math.max(1,Math.round(m.height*g[1])):l&&"height"in l?l.height:void 0,w=f.dimension??m?.dimension??"2d",S=w==="cube"?6:m?.depth??(l&&"depth"in l?l.depth:void 0),v=f.mipLevels??m?.mipLevels??1,T=f.samples??m?.samples??1,b=(s.get(d.id)??0)|d.usage;(0,D.assert)(T===1||!(b&(D.Texture.COPY_SRC|D.Texture.COPY_DST)));let P=i[d.id]??o[d.id];if(P===void 0){(0,D.assert)(d.role!=="input"&&!d.external&&y!==void 0&&p!==void 0&&b!==0),(0,D.assert)(Number.isSafeInteger(y)&&y>0&&Number.isSafeInteger(p)&&p>0);let E=e.createTexture({id:d.id,format:f.format,dimension:w,width:y,height:p,depth:S??1,mipLevels:v,samples:T,usage:b|(T===1?D.Texture.COPY_SRC:0)|D.Texture.SAMPLE});this.owned.add(E),P=E}(0,D.assert)(P instanceof D.Texture||P instanceof D.TextureView);let B=Q(P);(0,D.assert)(B.samples===1||!(b&(D.Texture.COPY_SRC|D.Texture.COPY_DST))),(0,D.assert)(B.texture.device===e&&B.format===f.format&&B.dimension===w&&(y===void 0||B.width===y)&&(p===void 0||B.height===p)&&(S===void 0||B.depth===S)&&(f.mipLevels===void 0&&d.role==="input"||B.mipLevels===v)&&(f.samples===void 0&&d.role==="input"||B.samples===T)&&(B.texture.props.usage&b)===b),this.values.set(d.id,P),u.delete(d),c=!0}(0,D.assert)(c)}for(let c of a){let d=Q(this.values.get(c)).texture;for(let[f,l]of this.values)(0,D.assert)(c===f||Q(l).texture!==d)}}catch(u){throw this.destroy(),u}}finish(e){for(let t of e){let n=this.values.get(t);n instanceof D.Texture&&this.owned.delete(n)}this.destroy()}destroy(){for(let e of this.owned)e.destroy();this.owned.clear()}};var zi=R(A(),1);function ji(r,e,t){let n=Q(e),o=Q(t);io(e,t);for(let i=0;i<n.mipLevels;i++)r.copyTextureToTexture({sourceTexture:n.texture,destinationTexture:o.texture,mipLevel:n.baseMipLevel+i,destinationMipLevel:o.baseMipLevel+i,origin:[0,0,n.baseArrayLayer],destinationOrigin:[0,0,o.baseArrayLayer],width:Math.max(1,n.width>>i),height:Math.max(1,n.height>>i),depthOrArrayLayers:n.dimension==="3d"?Math.max(1,n.depth>>i):n.depth})}function io(r,e){let t=Q(r),n=Q(e);(0,zi.assert)(t.texture!==n.texture&&t.samples===1&&n.samples===1&&t.format===n.format&&t.width===n.width&&t.height===n.height&&t.depth===n.depth&&t.mipLevels===n.mipLevels&&t.dimension===n.dimension)}var cr=R(A(),1);function Wi(r,e){let t=e.resolveVector(r.output),n=r.getData();for(let[o,i]of t.data.entries()){if(!i.length)continue;let s=n[o];e.graph.addCopyPass({id:`${r.id}-${o}`,resources:[{buffer:i,usage:"copy-destination"}],compile:({device:a})=>{let u=a.createBuffer({data:s,usage:cr.Buffer.COPY_SRC});return{encode:({commandEncoder:c,getBuffer:d})=>{let f=i.byteStride===i.rowByteLength;for(let l=0;l<i.length;l+=f?i.length:1)c.copyBufferToBuffer({sourceBuffer:u,sourceOffset:l*i.rowByteLength,destinationBuffer:d(i),destinationOffset:i.byteOffset+l*i.byteStride,size:f?s.byteLength:i.rowByteLength})},destroy:()=>u.destroy()}}})}}function Hi(r,e){let t=e.resolveVector(r.input),n=e.resolveVector(r.output);(0,cr.assert)(t.format===n.format&&t.data.length===n.data.length);for(let[o,i]of t.data.entries()){let s=n.data[o];(0,cr.assert)(i.length===s.length),i.length&&e.graph.addCopyPass({id:`${r.id}-${o}`,resources:[{buffer:i,usage:"copy-source"},{buffer:s,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:a,getBuffer:u})=>{let c=i.byteStride===i.rowByteLength&&s.byteStride===s.rowByteLength;for(let d=0;d<i.length;d+=c?i.length:1)a.copyBufferToBuffer({sourceBuffer:u(i),sourceOffset:i.byteOffset+d*i.byteStride,destinationBuffer:u(s),destinationOffset:s.byteOffset+d*s.byteStride,size:i.rowByteLength*(c?i.length:1)})}})})}}function qi(r,e){let t=e.resolveTextureView(r.input),n=e.resolveTextureView(r.output);e.graph.addCopyPass({id:r.id,resources:[{texture:t,usage:"copy-source"},{texture:n,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:o,getTextureView:i})=>ji(o,i(t),i(n))})})}var so=R(A(),1);var Ve=class{type="vector-upload";id;output;format;chunks;chunkLengths;constructor(e){this.id=e.id??`${e.output}-upload`,this.output=e.output,this.format=e.format;let t=I(e.format),n=Array.isArray(e.data)?e.data:[e.data],o=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array;(0,so.assert)(n.every(i=>i instanceof o&&i.byteLength%t.byteLength===0)),this.chunks=n.map(i=>new Uint8Array(i.buffer,i.byteOffset,i.byteLength).slice()),this.chunkLengths=Object.freeze(this.chunks.map(i=>i.byteLength/t.byteLength))}getData(){return this.chunks.map(e=>e.slice())}get contract(){let e={length:this.chunkLengths.reduce((t,n)=>t+n,0),chunkLengths:this.chunkLengths};return{outputs:{[this.output]:N.vector(this.format,e)},values:[{value:this.output,access:"write",shape:e}]}}},Ne=class{type="vector-copy";id;input;output;constructor(e){this.id=e.id??`${e.output}-copy`,this.input=e.input,this.output=e.output}get contract(){return{outputs:({getValue:e})=>{let t=e(this.input);return t.type==="texture"?{[this.output]:N.texture({...t,extent:{like:this.input}})}:((0,so.assert)(t.type==="vector"),{[this.output]:N.vector(t.format,{length:t.length,chunkLengths:t.chunkLengths})})},values:[{value:this.input,access:"read",textureUsage:"copy-source"},{value:this.output,access:"write",shape:{like:this.input},textureUsage:"copy-destination"}]}}};function W(r,e){let[t,n,o]=e;for(let[i,s]of[["x",t],["y",n],["z",o]])if(!Number.isSafeInteger(s)||s<0)throw new Error(`compute dispatch ${i} workgroup count must be a non-negative safe integer`);return{...r,dispatchWorkgroups:Object.freeze([t,n,o])}}function Vr(r){return r.dispatchWorkgroups}var ze=R(A(),1),F=class r{static async createAsync(e,t){let n=!ze.PipelineFactory.getAsyncCompilation(e),o=n?ze.PipelineFactory.beginAsyncCompilation(e):ze.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{n&&ze.PipelineFactory.endAsyncCompilation(e,o)}try{return n?await Promise.all(o):await i._pipelineInitialization,i}catch(s){throw i.destroy(),s}}device;id;source;pipelineFactory;shaderFactory;shader;pipeline;_pipelineInitialization;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Kernel is only supported in WebGPU");let{source:n,pipelineFactory:o,shaderFactory:i,debugShaders:s,...a}=t;this.device=e,this.id=t.id??"kernel",this.source=n,this.pipelineFactory=o??ze.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=i??ze.ShaderFactory.getDefaultShaderFactory(e),this.shader=this.shaderFactory.createShader({id:`${this.id}-compute`,stage:"compute",source:this.source,debugShaders:s});let u={...a,shader:this.shader},c=ze.PipelineFactory.getAsyncCompilation(e);if(c){let d=this.pipelineFactory.createComputePipelineAsync(u);this._pipelineInitialization=d,c.push(d.then(f=>(this.pipeline=f,f)))}else this.pipeline=this.pipelineFactory.createComputePipeline(u)}dispatch(e,t){this._setPipeline(e,t.bindings),e.dispatch(t.x,t.y,t.z)}dispatchIndirect(e,t){this._setPipeline(e,t.bindings),e.dispatchIndirect(t.indirectBuffer,t.indirectOffset??0)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._destroyed=!0)}_setPipeline(e,t={}){e.setPipeline(this.pipeline),e.setBindings(t)}};function je(r,e,t,n){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new Error(`${r} element count must be a non-negative uint32`);Yi(r,t);let o=Math.floor(n);if(!Number.isSafeInteger(o)||o<1)throw new Error("maxComputeWorkgroupsPerDimension must be a positive integer");let i=Math.max(1,Math.ceil(e/t)),s=Math.min(i,o),a=Math.min(Math.ceil(i/s),o),u=Math.ceil(i/s/a);if(u>o)throw new Error(`${r} requires ${i} workgroups, exceeding the 3D dispatch limit of ${o} per dimension`);return{x:s,y:a,z:u}}function me(r,e){Yi("GPU dispatch",e);let t=Math.floor(4294967295/e)+1;return`let workgroupIndex = (workgroupId.z * ${r.y}u + workgroupId.y) * ${r.x}u + workgroupId.x;
8
8
  if (workgroupIndex >= ${t}u) { return; }
9
- let index = workgroupIndex * ${e}u + localInvocationIndex;`}function Mi(r,e){if(!Number.isSafeInteger(e)||e<2||e>4294967295||4294967296%e!==0)throw new Error(`${r} workgroup size must be a power of two greater than one`)}var ro=V(R(),1);var no=Uint32Array.BYTES_PER_ELEMENT,oo=256;function mt(r,e,t){let n=U(r.format);if(!e.includes(r.format)||r.byteStride!==n.byteLength||r.rowByteLength!==n.byteLength||r.byteOffset%no!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function pt(r,e){mt(r,["uint32"],e)}function $(r,e){let t=sr(r),n={buffer:e(r),...t};if(n.offset+n.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return n}function sr(r){let e=Math.floor(r.byteOffset/oo)*oo,t=r.byteOffset-e,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(n,r.rowByteLength)}}function L(r){if(r.byteOffset%no!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%oo/no}function H(r,e,t,n,i=ro.Buffer.STORAGE){if(!Number.isSafeInteger(n)||n<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((i&ro.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(Je(t)||et(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let o=U(t),s=r.createTransientBuffer({id:e,byteLength:Math.max(n,1)*o.byteLength,usage:i});return r.createDataView(s,{format:t,length:n})}function io(r,e,t){let n,i=t.data.map((o,s)=>o.length===0?(n??=H(r,`${e}-empty`,t.format,0),n):H(r,`${e}-chunk-${s}`,t.format,o.length));return new D({id:e,name:e,format:t.format,length:t.length,valueLength:t.valueLength,stride:t.stride,byteStride:t.byteStride,rowByteLength:t.rowByteLength,data:i})}function Vi(r,e,t){if(!Number.isSafeInteger(t)||t<0||t>e.length)throw new Error("Graph prefix must fit within the input");if(t===e.length)return e;let n=e instanceof D?e.data:[e],i=t,o=[];for(let s of n){let a=Math.min(i,s.length);if(o.push(a===s.length?s:r.createDataView(s.buffer,{format:s.format,length:a,byteOffset:s.byteOffset,byteStride:s.byteStride,rowByteLength:s.rowByteLength})),i-=a,i===0)break}return e instanceof D?new D({...e,length:t,valueLength:t*(U(e.format).listSize??1),data:o}):o[0]}function Y(r){return r instanceof D?r.data:[r]}function ue(r,e){let t=e[0]?.length??0;if(e.some(u=>u.length!==t))throw new Error("Aligned vectors must have equal logical lengths");let n=e.map(Y),i=e.map(()=>0),o=e.map(()=>0),s=[],a=0;for(;a<t;){for(let d=0;d<n.length;d++)for(;n[d][i[d]]?.length===o[d];)i[d]++,o[d]=0;let u=n.map((d,l)=>d[i[l]]),c=Math.min(...u.map((d,l)=>d.length-o[l])),f=[];for(let d=0;d<u.length;d++){let l=u[d],h=u.findIndex((m,p)=>p<d&&m===l&&o[p]===o[d]);f.push(h>=0?f[h]:o[d]===0&&c===l.length?l:r.createDataView(l.buffer,{format:l.format,length:c,byteOffset:l.byteOffset+o[d]*l.byteStride,byteStride:l.byteStride,rowByteLength:l.rowByteLength}))}s.push(f);for(let d=0;d<o.length;d++)o[d]+=c;a+=c}return s}function Ut(r,e={}){let t=r.features?.has("subgroups"),n=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&n?"subgroups":"portable"}var Q=256,nu=64;function Ni(r,e=!1){return e?"portable":Ut(r,{requiresSubgroupId:!0})}var _r=class{id;input;output;mode;segmentFlags;constructor(e){if(this.id=e.id??"gpu-scan",this.input=e.input,this.output=e.output,this.mode=e.mode??"exclusive",this.segmentFlags=e.segmentFlags,ao(this.input,`${this.id} input`),ao(this.output,`${this.id} output`),this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.output instanceof D&&this.output.length!==this.input.length)throw new Error(`${this.id} vector output length must equal input length`);if(this.segmentFlags){if(ao(this.segmentFlags,`${this.id} segmentFlags`),this.segmentFlags.length<this.input.length)throw new Error(`${this.id} segmentFlags must contain at least input.length rows`);if(this.segmentFlags instanceof D&&this.segmentFlags.length!==this.input.length)throw new Error(`${this.id} vector segmentFlags length must equal input length`);let t=new Set(ji(this.output).map(n=>n.buffer));if(ji(this.segmentFlags).some(n=>t.has(n.buffer)))throw new Error(`${this.id} segmentFlags and output must use separate buffers`)}}getCommandNodes(e){let t=[];return t.push(...fo(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function fo(r,e,t){let n=[];uo(e,r.input,r.id),uo(e,r.output,r.id),r.segmentFlags&&uo(e,r.segmentFlags,r.id);let i=zi(e,r.output,r.input.length),o=r.segmentFlags?zi(e,r.segmentFlags,r.input.length):void 0,s=o?ue(e,[r.input,i,o]):ue(e,[r.input,i]);return n.push(...ou(e,{id:r.id,inputChunks:s.map(a=>a[0]),outputChunks:s.map(a=>a[1]),segmentFlagChunks:o?s.map(a=>a[2]):void 0,isVector:s.length>1,mode:r.mode},t)),n}function zi(r,e,t){return e.length===t||e instanceof D?e:r.createDataView(e.buffer,{format:e.format,length:t,byteOffset:e.byteOffset,byteStride:e.byteStride,rowByteLength:e.rowByteLength})}function ou(r,e,t){let n=[],i=e.inputChunks,o=e.outputChunks,s=e.segmentFlagChunks,a=i.map((l,h)=>({chunkIndex:h,input:l,output:o[h],segmentFlags:s?.[h]})).filter(l=>l.input.length>0);if(a.length===0)return n;if(a.length===1){let l=a[0];return n.push(...so(r,{id:e.isVector?`${e.id}-chunk-${l.chunkIndex}`:e.id,input:l.input,output:l.output,mode:e.mode,segmentFlags:l.segmentFlags,maxComputeWorkgroupsPerDimension:t})),n}let u=H(r,`${e.id}-chunk-totals`,"uint32",a.length),c=H(r,`${e.id}-chunk-offsets`,"uint32",a.length),f=s?H(r,`${e.id}-chunk-segment-flags`,"uint32",a.length):void 0,d=s?a.map(l=>H(r,`${e.id}-chunk-${l.chunkIndex}-segment-prefixes`,"uint32",l.input.length)):void 0;for(let[l,h]of a.entries())n.push(...so(r,{id:`${e.id}-chunk-${h.chunkIndex}`,input:h.input,output:h.output,mode:e.mode,segmentFlags:h.segmentFlags,outputSegmentPrefixes:d?.[l],finalSum:Wi(r,u,l),finalSegmentFlag:f?Wi(r,f,l):void 0,maxComputeWorkgroupsPerDimension:t}));n.push(...so(r,{id:`${e.id}-chunk-carries`,input:u,output:c,mode:"exclusive",segmentFlags:f,segmentSummaryInput:!!f,maxComputeWorkgroupsPerDimension:t}));for(let[l,h]of a.entries())n.push(...Hi(r,{id:`${e.id}-chunk-${h.chunkIndex}-add-carry`,output:h.output,offsets:c,length:h.output.length,offsetIndex:l,segmentPrefixes:d?.[l],dispatchLayout:co(h.output.length,t)}));return n}function so(r,e){let t=[];if(e.input.length===0)return t;let n=[],i=e.input,o=e.output,s=e.segmentFlags,a=e.input.length,u=0;for(;;){let c=Math.ceil(a/Q),f,d;c>1&&(f=H(r,`${e.id}-level-${u}-block-sums`,"uint32",c),s&&(d=H(r,`${e.id}-level-${u}-block-segment-flags`,"uint32",c)));let l=s?u===0&&e.outputSegmentPrefixes?e.outputSegmentPrefixes:c>1||u>0?H(r,`${e.id}-level-${u}-segment-prefixes`,"uint32",a):void 0:void 0;if(t.push(...iu(r,{id:`${e.id}-level-${u}-scan`,input:i,output:o,mode:u===0?e.mode:"exclusive",segmentFlags:s,segmentSummaryInput:!!s&&(u>0||e.segmentSummaryInput),segmentPrefixes:l,blockSums:f,blockSegmentFlags:d,finalSum:f?void 0:e.finalSum,finalSegmentFlag:f?void 0:e.finalSegmentFlag,length:a,blockCount:c,dispatchLayout:co(a,e.maxComputeWorkgroupsPerDimension)})),n.push({output:o,length:a,segmentPrefixes:l}),!f)break;let h=H(r,`${e.id}-level-${u}-block-offsets`,"uint32",c);n[n.length-1].blockOffsets=h,i=f,o=h,s=d,a=c,u++}for(let c=n.length-2;c>=0;c--){let f=n[c],d=n[c+1];t.push(...Hi(r,{id:`${e.id}-level-${c}-add-offsets`,output:f.output,offsets:f.blockOffsets,length:f.length,segmentPrefixes:f.segmentPrefixes,offsetSegmentPrefixes:d.segmentPrefixes,dispatchLayout:co(f.length,e.maxComputeWorkgroupsPerDimension)}))}return t}function Wi(r,e,t){return r.createDataView(e.buffer,{format:"uint32",length:1,byteOffset:e.byteOffset+t*e.rowByteLength})}function ao(r,e){let t=r instanceof D?r.data:[r];for(let n of t)pt(n,e)}function ji(r){return r instanceof D?r.data:[r]}function uo(r,e,t){if((e instanceof D?e.data:[e]).some(i=>i.buffer.graph!==r))throw new Error(`${t} views must belong to the target graph`)}function iu(r,e){let t=[],n=e.blockSums??e.finalSum,i=e.blockSegmentFlags??e.finalSegmentFlag,o=n?"@group(0) @binding(2) var<storage, read_write> sumValues: array<u32>;":"",s=e.segmentFlags?"@group(0) @binding(3) var<storage, read> segmentFlags: array<u32>;":"",a=e.segmentPrefixes?"@group(0) @binding(4) var<storage, read_write> segmentPrefixes: array<u32>;":"",u=i?"@group(0) @binding(5) var<storage, read_write> summarySegmentFlags: array<u32>;":"",c=e.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = scratch[255u];":e.finalSum?"sumValues[SUM_OFFSET] = scratch[255u];":"",f=e.blockSegmentFlags?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET + workgroupIndex] = segmentScratch[255u];":e.finalSegmentFlag?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET] = segmentScratch[255u];":"",d=e.segmentFlags?"segmentFlags[SEGMENT_FLAGS_OFFSET + index]":"0u",l=e.segmentFlags?`if (lane >= stride) {
9
+ let index = workgroupIndex * ${e}u + localInvocationIndex;`}function Yi(r,e){if(!Number.isSafeInteger(e)||e<2||e>4294967295||4294967296%e!==0)throw new Error(`${r} workgroup size must be a power of two greater than one`)}var ao=R(A(),1);var uo=Uint32Array.BYTES_PER_ELEMENT,co=256;function pt(r,e,t){let n=I(r.format);if(!e.includes(r.format)||r.byteStride!==n.byteLength||r.rowByteLength!==n.byteLength||r.byteOffset%uo!==0)throw new Error(`${t} must be packed, uint32-aligned ${e.join(" or ")} GPU data`)}function gt(r,e){pt(r,["uint32"],e)}function $(r,e){let t=dr(r),n={buffer:e(r),...t};if(n.offset+n.size>r.buffer.byteLength)throw new Error("GraphDataView storage binding exceeds its logical buffer");return n}function dr(r){let e=Math.floor(r.byteOffset/co)*co,t=r.byteOffset-e,n=r.length===0?r.rowByteLength:(r.length-1)*r.byteStride+r.rowByteLength;return{offset:e,size:t+Math.max(n,r.rowByteLength)}}function L(r){if(r.byteOffset%uo!==0)throw new Error("GraphDataView storage binding must be uint32-aligned");return r.byteOffset%co/uo}function q(r,e,t,n,o=ao.Buffer.STORAGE){if(!Number.isSafeInteger(n)||n<0)throw new Error("Transient GraphDataView length must be a non-negative safe integer");if((o&ao.Buffer.STORAGE)===0)throw new Error("Transient GraphDataView usage must include Buffer.STORAGE");if(et(t)||tt(t))throw new Error("Transient GraphDataView requires a fixed-width GPUVector format");let i=I(t),s=r.createTransientBuffer({id:e,byteLength:Math.max(n,1)*i.byteLength,usage:o});return r.createDataView(s,{format:t,length:n})}function fo(r,e,t){let n,o=t.data.map((i,s)=>i.length===0?(n??=q(r,`${e}-empty`,t.format,0),n):q(r,`${e}-chunk-${s}`,t.format,i.length));return new G({id:e,name:e,format:t.format,length:t.length,valueLength:t.valueLength,stride:t.stride,byteStride:t.byteStride,rowByteLength:t.rowByteLength,data:o})}function Xi(r,e,t){if(!Number.isSafeInteger(t)||t<0||t>e.length)throw new Error("Graph prefix must fit within the input");if(t===e.length)return e;let n=e instanceof G?e.data:[e],o=t,i=[];for(let s of n){let a=Math.min(o,s.length);if(i.push(a===s.length?s:r.createDataView(s.buffer,{format:s.format,length:a,byteOffset:s.byteOffset,byteStride:s.byteStride,rowByteLength:s.rowByteLength})),o-=a,o===0)break}return e instanceof G?new G({...e,length:t,valueLength:t*(I(e.format).listSize??1),data:i}):i[0]}function Y(r){return r instanceof G?r.data:[r]}function ce(r,e){let t=e[0]?.length??0;if(e.some(u=>u.length!==t))throw new Error("Aligned vectors must have equal logical lengths");let n=e.map(Y),o=e.map(()=>0),i=e.map(()=>0),s=[],a=0;for(;a<t;){for(let f=0;f<n.length;f++)for(;n[f][o[f]]?.length===i[f];)o[f]++,i[f]=0;let u=n.map((f,l)=>f[o[l]]),c=Math.min(...u.map((f,l)=>f.length-i[l])),d=[];for(let f=0;f<u.length;f++){let l=u[f],h=u.findIndex((m,g)=>g<f&&m===l&&i[g]===i[f]);d.push(h>=0?d[h]:i[f]===0&&c===l.length?l:r.createDataView(l.buffer,{format:l.format,length:c,byteOffset:l.byteOffset+i[f]*l.byteStride,byteStride:l.byteStride,rowByteLength:l.rowByteLength}))}s.push(d);for(let f=0;f<i.length;f++)i[f]+=c;a+=c}return s}function kt(r,e={}){let t=r.features?.has("subgroups"),n=!e.requiresSubgroupId||r.wgslLanguageFeatures?.has("subgroup_id");return t&&n?"subgroups":"portable"}var Z=256,pu=64;function Ki(r,e=!1){return e?"portable":kt(r,{requiresSubgroupId:!0})}var Nr=class{id;input;output;mode;segmentFlags;constructor(e){if(this.id=e.id??"gpu-scan",this.input=e.input,this.output=e.output,this.mode=e.mode??"exclusive",this.segmentFlags=e.segmentFlags,ho(this.input,`${this.id} input`),ho(this.output,`${this.id} output`),this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.output instanceof G&&this.output.length!==this.input.length)throw new Error(`${this.id} vector output length must equal input length`);if(this.segmentFlags){if(ho(this.segmentFlags,`${this.id} segmentFlags`),this.segmentFlags.length<this.input.length)throw new Error(`${this.id} segmentFlags must contain at least input.length rows`);if(this.segmentFlags instanceof G&&this.segmentFlags.length!==this.input.length)throw new Error(`${this.id} vector segmentFlags length must equal input length`);let t=new Set(Ji(this.output).map(n=>n.buffer));if(Ji(this.segmentFlags).some(n=>t.has(n.buffer)))throw new Error(`${this.id} segmentFlags and output must use separate buffers`)}}getCommandNodes(e){let t=[];return t.push(...go(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function go(r,e,t){let n=[];mo(e,r.input,r.id),mo(e,r.output,r.id),r.segmentFlags&&mo(e,r.segmentFlags,r.id);let o=Qi(e,r.output,r.input.length),i=r.segmentFlags?Qi(e,r.segmentFlags,r.input.length):void 0,s=i?ce(e,[r.input,o,i]):ce(e,[r.input,o]);return n.push(...gu(e,{id:r.id,inputChunks:s.map(a=>a[0]),outputChunks:s.map(a=>a[1]),segmentFlagChunks:i?s.map(a=>a[2]):void 0,isVector:s.length>1,mode:r.mode},t)),n}function Qi(r,e,t){return e.length===t||e instanceof G?e:r.createDataView(e.buffer,{format:e.format,length:t,byteOffset:e.byteOffset,byteStride:e.byteStride,rowByteLength:e.rowByteLength})}function gu(r,e,t){let n=[],o=e.inputChunks,i=e.outputChunks,s=e.segmentFlagChunks,a=o.map((l,h)=>({chunkIndex:h,input:l,output:i[h],segmentFlags:s?.[h]})).filter(l=>l.input.length>0);if(a.length===0)return n;if(a.length===1){let l=a[0];return n.push(...lo(r,{id:e.isVector?`${e.id}-chunk-${l.chunkIndex}`:e.id,input:l.input,output:l.output,mode:e.mode,segmentFlags:l.segmentFlags,maxComputeWorkgroupsPerDimension:t})),n}let u=q(r,`${e.id}-chunk-totals`,"uint32",a.length),c=q(r,`${e.id}-chunk-offsets`,"uint32",a.length),d=s?q(r,`${e.id}-chunk-segment-flags`,"uint32",a.length):void 0,f=s?a.map(l=>q(r,`${e.id}-chunk-${l.chunkIndex}-segment-prefixes`,"uint32",l.input.length)):void 0;for(let[l,h]of a.entries())n.push(...lo(r,{id:`${e.id}-chunk-${h.chunkIndex}`,input:h.input,output:h.output,mode:e.mode,segmentFlags:h.segmentFlags,outputSegmentPrefixes:f?.[l],finalSum:Zi(r,u,l),finalSegmentFlag:d?Zi(r,d,l):void 0,maxComputeWorkgroupsPerDimension:t}));n.push(...lo(r,{id:`${e.id}-chunk-carries`,input:u,output:c,mode:"exclusive",segmentFlags:d,segmentSummaryInput:!!d,maxComputeWorkgroupsPerDimension:t}));for(let[l,h]of a.entries())n.push(...es(r,{id:`${e.id}-chunk-${h.chunkIndex}-add-carry`,output:h.output,offsets:c,length:h.output.length,offsetIndex:l,segmentPrefixes:f?.[l],dispatchLayout:po(h.output.length,t)}));return n}function lo(r,e){let t=[];if(e.input.length===0)return t;let n=[],o=e.input,i=e.output,s=e.segmentFlags,a=e.input.length,u=0;for(;;){let c=Math.ceil(a/Z),d,f;c>1&&(d=q(r,`${e.id}-level-${u}-block-sums`,"uint32",c),s&&(f=q(r,`${e.id}-level-${u}-block-segment-flags`,"uint32",c)));let l=s?u===0&&e.outputSegmentPrefixes?e.outputSegmentPrefixes:c>1||u>0?q(r,`${e.id}-level-${u}-segment-prefixes`,"uint32",a):void 0:void 0;if(t.push(...yu(r,{id:`${e.id}-level-${u}-scan`,input:o,output:i,mode:u===0?e.mode:"exclusive",segmentFlags:s,segmentSummaryInput:!!s&&(u>0||e.segmentSummaryInput),segmentPrefixes:l,blockSums:d,blockSegmentFlags:f,finalSum:d?void 0:e.finalSum,finalSegmentFlag:d?void 0:e.finalSegmentFlag,length:a,blockCount:c,dispatchLayout:po(a,e.maxComputeWorkgroupsPerDimension)})),n.push({output:i,length:a,segmentPrefixes:l}),!d)break;let h=q(r,`${e.id}-level-${u}-block-offsets`,"uint32",c);n[n.length-1].blockOffsets=h,o=d,i=h,s=f,a=c,u++}for(let c=n.length-2;c>=0;c--){let d=n[c],f=n[c+1];t.push(...es(r,{id:`${e.id}-level-${c}-add-offsets`,output:d.output,offsets:d.blockOffsets,length:d.length,segmentPrefixes:d.segmentPrefixes,offsetSegmentPrefixes:f.segmentPrefixes,dispatchLayout:po(d.length,e.maxComputeWorkgroupsPerDimension)}))}return t}function Zi(r,e,t){return r.createDataView(e.buffer,{format:"uint32",length:1,byteOffset:e.byteOffset+t*e.rowByteLength})}function ho(r,e){let t=r instanceof G?r.data:[r];for(let n of t)gt(n,e)}function Ji(r){return r instanceof G?r.data:[r]}function mo(r,e,t){if((e instanceof G?e.data:[e]).some(o=>o.buffer.graph!==r))throw new Error(`${t} views must belong to the target graph`)}function yu(r,e){let t=[],n=e.blockSums??e.finalSum,o=e.blockSegmentFlags??e.finalSegmentFlag,i=n?"@group(0) @binding(2) var<storage, read_write> sumValues: array<u32>;":"",s=e.segmentFlags?"@group(0) @binding(3) var<storage, read> segmentFlags: array<u32>;":"",a=e.segmentPrefixes?"@group(0) @binding(4) var<storage, read_write> segmentPrefixes: array<u32>;":"",u=o?"@group(0) @binding(5) var<storage, read_write> summarySegmentFlags: array<u32>;":"",c=e.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = scratch[255u];":e.finalSum?"sumValues[SUM_OFFSET] = scratch[255u];":"",d=e.blockSegmentFlags?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET + workgroupIndex] = segmentScratch[255u];":e.finalSegmentFlag?"summarySegmentFlags[SUMMARY_SEGMENT_FLAGS_OFFSET] = segmentScratch[255u];":"",f=e.segmentFlags?"segmentFlags[SEGMENT_FLAGS_OFFSET + index]":"0u",l=e.segmentFlags?`if (lane >= stride) {
10
10
  scratch[lane] = select(addend + scratch[lane], scratch[lane], segmentScratch[lane] != 0u);
11
11
  segmentScratch[lane] = addendSegment | segmentScratch[lane];
12
12
  }`:`if (lane >= stride) {
@@ -16,7 +16,7 @@
16
16
  scannedOutput = scratch[lane - 1u];
17
17
  }
18
18
  ${e.segmentSummaryInput?"":"if (inputSegmentFlag != 0u) { scannedOutput = 0u; }"}
19
- outputValues[OUTPUT_OFFSET + index] = scannedOutput;`:`outputValues[OUTPUT_OFFSET + index] = ${h};`,p=e.segmentPrefixes?e.segmentSummaryInput?`var segmentPrefix = 0u;
19
+ outputValues[OUTPUT_OFFSET + index] = scannedOutput;`:`outputValues[OUTPUT_OFFSET + index] = ${h};`,g=e.segmentPrefixes?e.segmentSummaryInput?`var segmentPrefix = 0u;
20
20
  if (lane > 0u) {
21
21
  segmentPrefix = segmentScratch[lane - 1u];
22
22
  }
@@ -28,34 +28,34 @@ const OUTPUT_OFFSET: u32 = ${L(e.output)}u;
28
28
  ${n?`const SUM_OFFSET: u32 = ${L(n)}u;`:""}
29
29
  ${e.segmentFlags?`const SEGMENT_FLAGS_OFFSET: u32 = ${L(e.segmentFlags)}u;`:""}
30
30
  ${e.segmentPrefixes?`const SEGMENT_PREFIXES_OFFSET: u32 = ${L(e.segmentPrefixes)}u;`:""}
31
- ${i?`const SUMMARY_SEGMENT_FLAGS_OFFSET: u32 = ${L(i)}u;`:""}
31
+ ${o?`const SUMMARY_SEGMENT_FLAGS_OFFSET: u32 = ${L(o)}u;`:""}
32
32
  @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
33
33
  @group(0) @binding(1) var<storage, read_write> outputValues: array<u32>;
34
- ${o}
34
+ ${i}
35
35
  ${s}
36
36
  ${a}
37
37
  ${u}
38
- var<workgroup> scratch: array<u32, ${Q}>;
39
- ${e.segmentFlags?`var<workgroup> segmentScratch: array<u32, ${Q}>;`:""}
38
+ var<workgroup> scratch: array<u32, ${Z}>;
39
+ ${e.segmentFlags?`var<workgroup> segmentScratch: array<u32, ${Z}>;`:""}
40
40
 
41
- @compute @workgroup_size(${Q}) fn main(
41
+ @compute @workgroup_size(${Z}) fn main(
42
42
  @builtin(local_invocation_index) localInvocationIndex: u32,
43
43
  @builtin(workgroup_id) workgroupId: vec3<u32>
44
44
  ) {
45
- ${qi(e.dispatchLayout)}
45
+ ${ts(e.dispatchLayout)}
46
46
  if (workgroupIndex >= BLOCK_COUNT) { return; }
47
47
  let lane = localInvocationIndex;
48
48
  var inputValue = 0u;
49
49
  var inputSegmentFlag = 0u;
50
50
  if (index < ELEMENT_COUNT) {
51
51
  inputValue = inputValues[INPUT_OFFSET + index];
52
- inputSegmentFlag = ${d};
52
+ inputSegmentFlag = ${f};
53
53
  }
54
54
  scratch[lane] = inputValue;
55
55
  ${e.segmentFlags?"segmentScratch[lane] = inputSegmentFlag;":""}
56
56
  workgroupBarrier();
57
57
 
58
- for (var stride = 1u; stride < ${Q}u; stride = stride * 2u) {
58
+ for (var stride = 1u; stride < ${Z}u; stride = stride * 2u) {
59
59
  var addend = 0u;
60
60
  ${e.segmentFlags?"var addendSegment = 0u;":""}
61
61
  if (lane >= stride) {
@@ -67,15 +67,15 @@ ${e.segmentFlags?`var<workgroup> segmentScratch: array<u32, ${Q}>;`:""}
67
67
  workgroupBarrier();
68
68
  }
69
69
 
70
- if (lane == ${Q-1}u) {
70
+ if (lane == ${Z-1}u) {
71
71
  ${c}
72
- ${f}
72
+ ${d}
73
73
  }
74
74
  if (index < ELEMENT_COUNT) {
75
75
  ${m}
76
- ${p}
76
+ ${g}
77
77
  }
78
- }`,g=su(r,!!e.segmentFlags,e.length),w=g==="subgroups"?au(e,n,o):y;return t.push(N({id:e.id,workload:{operation:"GPUScan",variant:g,commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Q,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT+e.blockCount*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...n?[{buffer:n,usage:"storage-write"}]:[],...e.segmentFlags?[{buffer:e.segmentFlags,usage:"storage-read"}]:[],...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:"storage-write"}]:[],...i?[{buffer:i,usage:"storage-write"}]:[]],compile:({device:S})=>{let v=new _(S,{id:e.id,source:w,shaderLayout:{bindings:[{name:"inputValues",type:"storage",group:0,location:0},{name:"outputValues",type:"storage",group:0,location:1},...n?[{name:"sumValues",type:"storage",group:0,location:2}]:[],...e.segmentFlags?[{name:"segmentFlags",type:"storage",group:0,location:3}]:[],...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:4}]:[],...i?[{name:"summarySegmentFlags",type:"storage",group:0,location:5}]:[]]}});return{encode:({computePass:T,getBuffer:b})=>{let P={inputValues:$(e.input,b),outputValues:$(e.output,b)};n&&(P.sumValues=$(n,b)),e.segmentFlags&&(P.segmentFlags=$(e.segmentFlags,b)),e.segmentPrefixes&&(P.segmentPrefixes=$(e.segmentPrefixes,b)),i&&(P.summarySegmentFlags=$(i,b)),v.dispatch(T,{bindings:P,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>v.destroy()}}})),t.map(S=>z(S,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function su(r,e,t){let n=Ni(r.device,e);if(!r.autotuner||e)return n;let i=n==="subgroups"?"portable":"subgroups";return r.autotuner.selectKernel({operation:"GPUScan",workloadSize:t,candidates:[{id:n},{id:i,supported:i==="portable"||Ni(r.device,!1)==="subgroups"}]}).variant}function au(r,e,t){let n=r.mode==="inclusive"?"blockPrefix":"blockPrefix - inputValue",i=r.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = blockPrefix;":r.finalSum?"sumValues[SUM_OFFSET] = blockPrefix;":"",o=Math.floor(4294967295/Q)+1;return`
78
+ }`,p=bu(r,!!e.segmentFlags,e.length),w=p==="subgroups"?xu(e,n,i):y;return t.push(j({id:e.id,workload:{operation:"GPUScan",variant:p,commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Z,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT+e.blockCount*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...n?[{buffer:n,usage:"storage-write"}]:[],...e.segmentFlags?[{buffer:e.segmentFlags,usage:"storage-read"}]:[],...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:"storage-write"}]:[],...o?[{buffer:o,usage:"storage-write"}]:[]],compile:({device:S})=>{let v=new F(S,{id:e.id,source:w,shaderLayout:{bindings:[{name:"inputValues",type:"storage",group:0,location:0},{name:"outputValues",type:"storage",group:0,location:1},...n?[{name:"sumValues",type:"storage",group:0,location:2}]:[],...e.segmentFlags?[{name:"segmentFlags",type:"storage",group:0,location:3}]:[],...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:4}]:[],...o?[{name:"summarySegmentFlags",type:"storage",group:0,location:5}]:[]]}});return{encode:({computePass:T,getBuffer:b})=>{let P={inputValues:$(e.input,b),outputValues:$(e.output,b)};n&&(P.sumValues=$(n,b)),e.segmentFlags&&(P.segmentFlags=$(e.segmentFlags,b)),e.segmentPrefixes&&(P.segmentPrefixes=$(e.segmentPrefixes,b)),o&&(P.summarySegmentFlags=$(o,b)),v.dispatch(T,{bindings:P,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>v.destroy()}}})),t.map(S=>W(S,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function bu(r,e,t){let n=Ki(r.device,e);if(!r.autotuner||e)return n;let o=n==="subgroups"?"portable":"subgroups";return r.autotuner.selectKernel({operation:"GPUScan",workloadSize:t,candidates:[{id:n},{id:o,supported:o==="portable"||Ki(r.device,!1)==="subgroups"}]}).variant}function xu(r,e,t){let n=r.mode==="inclusive"?"blockPrefix":"blockPrefix - inputValue",o=r.blockSums?"sumValues[SUM_OFFSET + workgroupIndex] = blockPrefix;":r.finalSum?"sumValues[SUM_OFFSET] = blockPrefix;":"",i=Math.floor(4294967295/Z)+1;return`
79
79
  enable subgroups;
80
80
  requires subgroup_id;
81
81
 
@@ -87,18 +87,18 @@ ${e?`const SUM_OFFSET: u32 = ${L(e)}u;`:""}
87
87
  @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
88
88
  @group(0) @binding(1) var<storage, read_write> outputValues: array<u32>;
89
89
  ${t}
90
- var<workgroup> subgroupOffsets: array<u32, ${nu}>;
90
+ var<workgroup> subgroupOffsets: array<u32, ${pu}>;
91
91
 
92
- @compute @workgroup_size(${Q}) fn main(
92
+ @compute @workgroup_size(${Z}) fn main(
93
93
  @builtin(subgroup_invocation_id) subgroupInvocationId: u32,
94
94
  @builtin(subgroup_size) subgroupSize: u32,
95
95
  @builtin(subgroup_id) subgroupId: u32,
96
96
  @builtin(workgroup_id) workgroupId: vec3<u32>
97
97
  ) {
98
98
  let workgroupIndex = (workgroupId.z * ${r.dispatchLayout.y}u + workgroupId.y) * ${r.dispatchLayout.x}u + workgroupId.x;
99
- if (workgroupIndex >= ${o}u || workgroupIndex >= BLOCK_COUNT) { return; }
99
+ if (workgroupIndex >= ${i}u || workgroupIndex >= BLOCK_COUNT) { return; }
100
100
  let lane = subgroupId * subgroupSize + subgroupInvocationId;
101
- let index = workgroupIndex * ${Q}u + lane;
101
+ let index = workgroupIndex * ${Z}u + lane;
102
102
  var inputValue = 0u;
103
103
  if (index < ELEMENT_COUNT) {
104
104
  inputValue = inputValues[INPUT_OFFSET + index];
@@ -110,7 +110,7 @@ var<workgroup> subgroupOffsets: array<u32, ${nu}>;
110
110
  }
111
111
  workgroupBarrier();
112
112
 
113
- let subgroupCount = ${Q}u / subgroupSize;
113
+ let subgroupCount = ${Z}u / subgroupSize;
114
114
  if (lane == 0u) {
115
115
  var runningOffset = 0u;
116
116
  for (var subgroupIndex = 0u; subgroupIndex < subgroupCount; subgroupIndex++) {
@@ -122,13 +122,13 @@ var<workgroup> subgroupOffsets: array<u32, ${nu}>;
122
122
  workgroupBarrier();
123
123
 
124
124
  let blockPrefix = subgroupOffsets[subgroupId] + subgroupPrefix;
125
- if (lane == ${Q-1}u) {
126
- ${i}
125
+ if (lane == ${Z-1}u) {
126
+ ${o}
127
127
  }
128
128
  if (index < ELEMENT_COUNT) {
129
129
  outputValues[OUTPUT_OFFSET + index] = ${n};
130
130
  }
131
- }`}function Hi(r,e){let t=[],n=e.offsetIndex===void 0?`index / ${Q}u`:`${e.offsetIndex}u`,i=`
131
+ }`}function es(r,e){let t=[],n=e.offsetIndex===void 0?`index / ${Z}u`:`${e.offsetIndex}u`,o=`
132
132
  const ELEMENT_COUNT: u32 = ${e.length}u;
133
133
  const OUTPUT_OFFSET: u32 = ${L(e.output)}u;
134
134
  const OFFSETS_OFFSET: u32 = ${L(e.offsets)}u;
@@ -139,11 +139,11 @@ ${e.offsetSegmentPrefixes?`const OFFSET_SEGMENT_PREFIXES_OFFSET: u32 = ${L(e.off
139
139
  ${e.segmentPrefixes?`@group(0) @binding(2) var<storage, ${e.offsetSegmentPrefixes?"read_write":"read"}> segmentPrefixes: array<u32>;`:""}
140
140
  ${e.offsetSegmentPrefixes?"@group(0) @binding(3) var<storage, read> offsetSegmentPrefixes: array<u32>;":""}
141
141
 
142
- @compute @workgroup_size(${Q}) fn main(
142
+ @compute @workgroup_size(${Z}) fn main(
143
143
  @builtin(local_invocation_index) localInvocationIndex: u32,
144
144
  @builtin(workgroup_id) workgroupId: vec3<u32>
145
145
  ) {
146
- ${qi(e.dispatchLayout)}
146
+ ${ts(e.dispatchLayout)}
147
147
  if (index < ELEMENT_COUNT) {
148
148
  ${e.offsetSegmentPrefixes?`let offsetSegmentPrefix = offsetSegmentPrefixes[OFFSET_SEGMENT_PREFIXES_OFFSET + ${n}];`:""}
149
149
  ${e.segmentPrefixes?`let segmentPrefix = segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index];
@@ -152,21 +152,21 @@ ${e.offsetSegmentPrefixes?"@group(0) @binding(3) var<storage, read> offsetSegmen
152
152
  ${e.segmentPrefixes?"}":""}
153
153
  ${e.segmentPrefixes&&e.offsetSegmentPrefixes?"segmentPrefixes[SEGMENT_PREFIXES_OFFSET + index] = segmentPrefix | offsetSegmentPrefix;":""}
154
154
  }
155
- }`;return t.push(N({id:e.id,workload:{operation:"GPUScan",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Q,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT*2,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.output,usage:"storage-read-write"},{buffer:e.offsets,usage:"storage-read"},...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:e.offsetSegmentPrefixes?"storage-read-write":"storage-read"}]:[],...e.offsetSegmentPrefixes?[{buffer:e.offsetSegmentPrefixes,usage:"storage-read"}]:[]],compile:({device:o})=>{let s=new _(o,{id:e.id,source:i,shaderLayout:{bindings:[{name:"outputValues",type:"storage",group:0,location:0},{name:"offsets",type:"storage",group:0,location:1},...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:2}]:[],...e.offsetSegmentPrefixes?[{name:"offsetSegmentPrefixes",type:"storage",group:0,location:3}]:[]]}});return{encode:({computePass:a,getBuffer:u})=>{let c={outputValues:$(e.output,u),offsets:$(e.offsets,u)};e.segmentPrefixes&&(c.segmentPrefixes=$(e.segmentPrefixes,u)),e.offsetSegmentPrefixes&&(c.offsetSegmentPrefixes=$(e.offsetSegmentPrefixes,u)),s.dispatch(a,{bindings:c,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>s.destroy()}}})),t.map(o=>z(o,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function co(r,e){return ze("GPUScan",r,Q,e)}function qi(r){return he(r,Q)}var yt=256,Fr=class{id;input;flags;output;count;constructor(e){if(this.id=e.id??"gpu-compaction",this.input=e.input,this.flags=e.flags,this.output=e.output,this.count=e.count,lo(this.input,`${this.id} input`),lo(this.flags,`${this.id} flags`),lo(this.output,`${this.id} output`),pt(this.count,`${this.id} count`),this.flags.length!==this.input.length)throw new Error(`${this.id} flags.length must equal input.length`);if(this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.count.length<1)throw new Error(`${this.id} count must contain one uint32 row`)}getCommandNodes(e){let t=[];return t.push(...uu(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function uu(r,e,t){let n=[];for(let a of[...gt(r.input),...gt(r.flags),...gt(r.output),r.count])if(a.buffer.graph!==e)throw new Error(`${r.id} views must belong to the target graph`);if(r.input.length===0)return n.push(...cu(e,r.id,r.count)),n;let i=r.flags instanceof D?io(e,`${r.id}-offsets`,r.flags):H(e,`${r.id}-offsets`,"uint32",r.flags.length),o=r.flags instanceof D?io(e,`${r.id}-flags`,r.flags):H(e,`${r.id}-flags`,"uint32",r.flags.length);for(let[a,u]of gt(r.flags).entries()){if(!u.length)continue;let c=gt(o)[a],f=ze(r.id,u.length,yt,t);n.push(...Yi(e,{id:`${r.id}-normalize-${a}`,source:`
155
+ }`;return t.push(j({id:e.id,workload:{operation:"GPUScan",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*Z,readByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT*2,writeByteLength:e.length*Uint32Array.BYTES_PER_ELEMENT},resources:[{buffer:e.output,usage:"storage-read-write"},{buffer:e.offsets,usage:"storage-read"},...e.segmentPrefixes?[{buffer:e.segmentPrefixes,usage:e.offsetSegmentPrefixes?"storage-read-write":"storage-read"}]:[],...e.offsetSegmentPrefixes?[{buffer:e.offsetSegmentPrefixes,usage:"storage-read"}]:[]],compile:({device:i})=>{let s=new F(i,{id:e.id,source:o,shaderLayout:{bindings:[{name:"outputValues",type:"storage",group:0,location:0},{name:"offsets",type:"storage",group:0,location:1},...e.segmentPrefixes?[{name:"segmentPrefixes",type:"storage",group:0,location:2}]:[],...e.offsetSegmentPrefixes?[{name:"offsetSegmentPrefixes",type:"storage",group:0,location:3}]:[]]}});return{encode:({computePass:a,getBuffer:u})=>{let c={outputValues:$(e.output,u),offsets:$(e.offsets,u)};e.segmentPrefixes&&(c.segmentPrefixes=$(e.segmentPrefixes,u)),e.offsetSegmentPrefixes&&(c.offsetSegmentPrefixes=$(e.offsetSegmentPrefixes,u)),s.dispatch(a,{bindings:c,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>s.destroy()}}})),t.map(i=>W(i,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function po(r,e){return je("GPUScan",r,Z,e)}function ts(r){return me(r,Z)}var bt=256,zr=class{id;input;flags;output;count;constructor(e){if(this.id=e.id??"gpu-compaction",this.input=e.input,this.flags=e.flags,this.output=e.output,this.count=e.count,yo(this.input,`${this.id} input`),yo(this.flags,`${this.id} flags`),yo(this.output,`${this.id} output`),gt(this.count,`${this.id} count`),this.flags.length!==this.input.length)throw new Error(`${this.id} flags.length must equal input.length`);if(this.output.length<this.input.length)throw new Error(`${this.id} output must contain at least input.length rows`);if(this.count.length<1)throw new Error(`${this.id} count must contain one uint32 row`)}getCommandNodes(e){let t=[];return t.push(...wu(this,e,e.device.limits.maxComputeWorkgroupsPerDimension)),t}};function wu(r,e,t){let n=[];for(let a of[...yt(r.input),...yt(r.flags),...yt(r.output),r.count])if(a.buffer.graph!==e)throw new Error(`${r.id} views must belong to the target graph`);if(r.input.length===0)return n.push(...Tu(e,r.id,r.count)),n;let o=r.flags instanceof G?fo(e,`${r.id}-offsets`,r.flags):q(e,`${r.id}-offsets`,"uint32",r.flags.length),i=r.flags instanceof G?fo(e,`${r.id}-flags`,r.flags):q(e,`${r.id}-flags`,"uint32",r.flags.length);for(let[a,u]of yt(r.flags).entries()){if(!u.length)continue;let c=yt(i)[a],d=je(r.id,u.length,bt,t);n.push(...rs(e,{id:`${r.id}-normalize-${a}`,source:`
156
156
  @group(0) @binding(0) var<storage, read> inputValues: array<u32>;
157
157
  @group(0) @binding(1) var<storage, read_write> outputValues: array<u32>;
158
- @compute @workgroup_size(${yt}) fn main(
158
+ @compute @workgroup_size(${bt}) fn main(
159
159
  @builtin(local_invocation_index) localInvocationIndex: u32,
160
160
  @builtin(workgroup_id) workgroupId: vec3<u32>
161
161
  ) {
162
- ${he(f,yt)}
162
+ ${me(d,bt)}
163
163
  if (index >= ${u.length}u) { return; }
164
164
  outputValues[${L(c)}u + index] = min(inputValues[${L(u)}u + index], 1u);
165
- }`,resources:[{buffer:u,usage:"storage-read"},{buffer:c,usage:"storage-write"}],bindings:{inputValues:u,outputValues:c},dispatchLayout:f}))}let s=new _r({id:`${r.id}-scan`,input:o,output:i});return n.push(...fo(s,e,t)),n.push(...du(e,r.id,r.input,r.flags,i,r.output,r.count,t)),n}function cu(r,e,t){let n=[],i=`${e}-clear-count`;return n.push(N({id:i,resources:[{buffer:t,usage:"storage-write"}],compile:({device:o})=>{let s=new _(o,{id:i,source:`const COUNT_OFFSET: u32 = ${L(t)}u;
165
+ }`,resources:[{buffer:u,usage:"storage-read"},{buffer:c,usage:"storage-write"}],bindings:{inputValues:u,outputValues:c},dispatchLayout:d}))}let s=new Nr({id:`${r.id}-scan`,input:i,output:o});return n.push(...go(s,e,t)),n.push(...vu(e,r.id,r.input,r.flags,o,r.output,r.count,t)),n}function Tu(r,e,t){let n=[],o=`${e}-clear-count`;return n.push(j({id:o,resources:[{buffer:t,usage:"storage-write"}],compile:({device:i})=>{let s=new F(i,{id:o,source:`const COUNT_OFFSET: u32 = ${L(t)}u;
166
166
  @group(0) @binding(0) var<storage, read_write> outputCount: array<u32>;
167
- @compute @workgroup_size(1) fn main() { outputCount[COUNT_OFFSET] = 0u; }`,shaderLayout:{bindings:[{name:"outputCount",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{s.dispatch(a,{bindings:{outputCount:$(t,u)},x:1})},destroy:()=>s.destroy()}}})),n.map(o=>z(o,[1,1,1]))}function du(r,e,t,n,i,o,s,a){let u=[],c=ue(r,[t,n,i]),f=c.map(v=>v[0]),d=c.map(v=>v[1]),l=c.map(v=>v[2]),h=gt(o),m=f.map((v,T)=>v.length>0?T:-1).filter(v=>v>=0),p=h.map((v,T)=>v.length>0?T:-1).filter(v=>v>=0),y=m[m.length-1],g=p[p.length-1],w=c.length>1||o instanceof D,S=0;for(let v=0;v<h.length;v++){let T=h[v],b=S+T.length;if(T.length>0)for(let P of m){let B=P===y&&v===g;u.push(...fu(r,{id:w?`${e}-scatter-input-${P}-output-${v}`:`${e}-scatter`,input:f[P],flags:d[P],offsets:l[P],output:T,outputStart:S,outputEnd:b,count:B?s:void 0,dispatchLayout:ze("GPUCompaction",f[P].length,yt,a)}))}S=b}return u}function fu(r,e){let t=[],n=e.count?"@group(0) @binding(4) var<storage, read_write> outputCount: array<u32>;":"",i=e.count?`if (index == ELEMENT_COUNT - 1u) {
167
+ @compute @workgroup_size(1) fn main() { outputCount[COUNT_OFFSET] = 0u; }`,shaderLayout:{bindings:[{name:"outputCount",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{s.dispatch(a,{bindings:{outputCount:$(t,u)},x:1})},destroy:()=>s.destroy()}}})),n.map(i=>W(i,[1,1,1]))}function vu(r,e,t,n,o,i,s,a){let u=[],c=ce(r,[t,n,o]),d=c.map(v=>v[0]),f=c.map(v=>v[1]),l=c.map(v=>v[2]),h=yt(i),m=d.map((v,T)=>v.length>0?T:-1).filter(v=>v>=0),g=h.map((v,T)=>v.length>0?T:-1).filter(v=>v>=0),y=m[m.length-1],p=g[g.length-1],w=c.length>1||i instanceof G,S=0;for(let v=0;v<h.length;v++){let T=h[v],b=S+T.length;if(T.length>0)for(let P of m){let B=P===y&&v===p;u.push(...Su(r,{id:w?`${e}-scatter-input-${P}-output-${v}`:`${e}-scatter`,input:d[P],flags:f[P],offsets:l[P],output:T,outputStart:S,outputEnd:b,count:B?s:void 0,dispatchLayout:je("GPUCompaction",d[P].length,bt,a)}))}S=b}return u}function Su(r,e){let t=[],n=e.count?"@group(0) @binding(4) var<storage, read_write> outputCount: array<u32>;":"",o=e.count?`if (index == ELEMENT_COUNT - 1u) {
168
168
  outputCount[COUNT_OFFSET] = outputIndex + flag;
169
- }`:"",o=`
169
+ }`:"",i=`
170
170
  const ELEMENT_COUNT: u32 = ${e.input.length}u;
171
171
  const INPUT_OFFSET: u32 = ${L(e.input)}u;
172
172
  const FLAGS_OFFSET: u32 = ${L(e.flags)}u;
@@ -181,67 +181,67 @@ ${e.count?`const COUNT_OFFSET: u32 = ${L(e.count)}u;`:""}
181
181
  @group(0) @binding(3) var<storage, read_write> outputValues: array<u32>;
182
182
  ${n}
183
183
 
184
- @compute @workgroup_size(${yt}) fn main(
184
+ @compute @workgroup_size(${bt}) fn main(
185
185
  @builtin(local_invocation_index) localInvocationIndex: u32,
186
186
  @builtin(workgroup_id) workgroupId: vec3<u32>
187
187
  ) {
188
- ${he(e.dispatchLayout,yt)}
188
+ ${me(e.dispatchLayout,bt)}
189
189
  if (index >= ELEMENT_COUNT) { return; }
190
190
  let flag = min(flags[FLAGS_OFFSET + index], 1u);
191
191
  let outputIndex = offsets[OFFSETS_OFFSET + index];
192
192
  if (flag != 0u && outputIndex >= OUTPUT_START && outputIndex < OUTPUT_END) {
193
193
  outputValues[OUTPUT_OFFSET + outputIndex - OUTPUT_START] = inputValues[INPUT_OFFSET + index];
194
194
  }
195
- ${i}
196
- }`;return t.push(...Yi(r,{id:e.id,source:o,resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.flags,usage:"storage-read"},{buffer:e.offsets,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...e.count?[{buffer:e.count,usage:"storage-write"}]:[]],bindings:{inputValues:e.input,flags:e.flags,offsets:e.offsets,outputValues:e.output,...e.count?{outputCount:e.count}:{}},dispatchLayout:e.dispatchLayout})),t}function Yi(r,e){let t=[];return t.push(N({id:e.id,workload:{operation:"GPUCompaction",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*yt,readByteLength:e.resources.reduce((n,i)=>n+(i.usage==="storage-read"||i.usage==="storage-read-write"?i.buffer.length*i.buffer.rowByteLength:0),0),writeByteLength:e.resources.reduce((n,i)=>n+(i.usage==="storage-write"||i.usage==="storage-read-write"?i.buffer.length*i.buffer.rowByteLength:0),0)},resources:e.resources,compile:({device:n})=>{let i=new _(n,{id:e.id,source:e.source,shaderLayout:{bindings:Object.keys(e.bindings).map((o,s)=>({name:o,type:"storage",group:0,location:s}))}});return{encode:({computePass:o,getBuffer:s})=>{let a={};for(let[u,c]of Object.entries(e.bindings))a[u]=$(c,s);i.dispatch(o,{bindings:a,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>i.destroy()}}})),t.map(n=>z(n,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function gt(r){return r instanceof D?r.data:[r]}function lo(r,e){for(let t of gt(r))pt(t,e)}var se=V(R(),1);var Rr=class extends ht{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addCopyPass(t)}withOtherLowering(e,t){this.otherLowerings.push(e);try{return t()}finally{this.otherLowerings.pop()}}constructor(e,t={}){super(e,t)}addComputePass(e){let t=e;if(this.loweringsSuspended===0)for(let n=this.computeLowerings.length-1;n>=0;n--)t=this.computeLowerings[n](t);super.addComputePass(t)}withComputeLowering(e,t){this.computeLowerings.push(e);try{return t()}finally{this.computeLowerings.pop()}}withoutComputeLowering(e){this.loweringsSuspended++;try{return e()}finally{this.loweringsSuspended--}}};var Vr=V(R(),1);var Mr=V(R(),1);var lu=16*1024,Xi=new WeakMap;function Ki(r){let e=r,t=Xi.get(e);return t||(t=new ho(r),Xi.set(e,t)),t}var ho=class{id;graph;buffer;capacityByteLength;nextByteOffset=0;slots=new Map;views=new Map;constructor(e,t="gpu-value-arena",n=lu){if(this.id=t,this.graph=e,!Number.isSafeInteger(n)||n<=0||n%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=n,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:n,usage:Mr.Buffer.STORAGE|Mr.Buffer.COPY_SRC|Mr.Buffer.COPY_DST})}allocate(e,t){if(!e)throw new Error(`${this.id} slot id must not be empty`);if(this.slots.has(e))throw new Error(`${this.id} slot "${e}" already exists`);if(!["float32","uint32","sint32"].includes(t))throw new Error(`${this.id} unsupported slot format ${t}`);if(this.nextByteOffset+4>this.capacityByteLength)throw new Error(`${this.id} capacity exceeded while allocating "${e}"`);let n=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,n),this.views.set(e,new Ge(this.buffer,{format:t,length:1,byteOffset:n.byteOffset,byteStride:4,rowByteLength:4})),n}get(e){return this.slots.get(e)}getSlots(){return Object.freeze([...this.slots.values()])}getView(e){let t=this.views.get(e.id);if(!t)throw new Error(`${this.id} does not contain slot "${e.id}"`);return t}get byteLength(){return this.nextByteOffset}get size(){return this.slots.size}get availableByteLength(){return this.capacityByteLength-this.nextByteOffset}};var mo=class{id;format;arena;slot;constructor(e,t){this.id=t.id,this.format=t.format,this.arena=e,this.slot=t}get byteOffset(){return this.slot.byteOffset}get wordOffset(){return this.slot.byteOffset>>>2}get view(){return this.arena.getView(this.slot)}};function po(r,e,t){let n=Ki(r);return new mo(n,n.allocate(e,t))}function Se(r,e="gpuValues"){let t=`${e}[${r.wordOffset}u]`;switch(r.format){case"float32":return`bitcast<f32>(${t})`;case"uint32":return t;case"sint32":return`bitcast<i32>(${t})`}}function ot(r,e,t="gpuValues"){let n=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${n} = bitcast<u32>(${e});`;case"uint32":return`${n} = ${e};`;case"sint32":return`${n} = bitcast<u32>(${e});`}}function me(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var ar=class{id;active;workgroups;dispatchBuffer;constructor(e,t){if(this.id=t.id,this.active=t.active,this.workgroups=t.workgroups,t.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);this.dispatchBuffer=e.createTransientBuffer({id:`${this.id}-dispatch`,byteLength:12,usage:Vr.Buffer.STORAGE|Vr.Buffer.INDIRECT|Vr.Buffer.COPY_SRC})}getUpdateCommandNodes(e,t=`${this.id}-update`){if(this.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);let n=this.active.arena.buffer,[i,o,s]=this.workgroups,a=`${me(0,0)}
195
+ ${o}
196
+ }`;return t.push(...rs(r,{id:e.id,source:i,resources:[{buffer:e.input,usage:"storage-read"},{buffer:e.flags,usage:"storage-read"},{buffer:e.offsets,usage:"storage-read"},{buffer:e.output,usage:"storage-write"},...e.count?[{buffer:e.count,usage:"storage-write"}]:[]],bindings:{inputValues:e.input,flags:e.flags,offsets:e.offsets,outputValues:e.output,...e.count?{outputCount:e.count}:{}},dispatchLayout:e.dispatchLayout})),t}function rs(r,e){let t=[];return t.push(j({id:e.id,workload:{operation:"GPUCompaction",commandCount:1,maximumWorkgroupCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z,maximumInvocationCount:e.dispatchLayout.x*e.dispatchLayout.y*e.dispatchLayout.z*bt,readByteLength:e.resources.reduce((n,o)=>n+(o.usage==="storage-read"||o.usage==="storage-read-write"?o.buffer.length*o.buffer.rowByteLength:0),0),writeByteLength:e.resources.reduce((n,o)=>n+(o.usage==="storage-write"||o.usage==="storage-read-write"?o.buffer.length*o.buffer.rowByteLength:0),0)},resources:e.resources,compile:({device:n})=>{let o=new F(n,{id:e.id,source:e.source,shaderLayout:{bindings:Object.keys(e.bindings).map((i,s)=>({name:i,type:"storage",group:0,location:s}))}});return{encode:({computePass:i,getBuffer:s})=>{let a={};for(let[u,c]of Object.entries(e.bindings))a[u]=$(c,s);o.dispatch(i,{bindings:a,x:e.dispatchLayout.x,y:e.dispatchLayout.y,z:e.dispatchLayout.z})},destroy:()=>o.destroy()}}})),t.map(n=>W(n,[e.dispatchLayout.x,e.dispatchLayout.y,e.dispatchLayout.z]))}function yt(r){return r instanceof G?r.data:[r]}function yo(r,e){for(let t of yt(r))gt(t,e)}var ue=R(A(),1);var jr=class extends mt{computeLowerings=[];loweringsSuspended=0;otherLowerings=[];addRenderPass(e){let t={...e,type:"render"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addRenderPass(t)}addCopyPass(e){let t={...e,type:"copy"},n=this.otherLowerings.at(-1);n&&(t=n(t)),super.addCopyPass(t)}withOtherLowering(e,t){this.otherLowerings.push(e);try{return t()}finally{this.otherLowerings.pop()}}constructor(e,t={}){super(e,t)}addComputePass(e){let t=e;if(this.loweringsSuspended===0)for(let n=this.computeLowerings.length-1;n>=0;n--)t=this.computeLowerings[n](t);super.addComputePass(t)}withComputeLowering(e,t){this.computeLowerings.push(e);try{return t()}finally{this.computeLowerings.pop()}}withoutComputeLowering(e){this.loweringsSuspended++;try{return e()}finally{this.loweringsSuspended--}}};var Hr=R(A(),1);var Wr=R(A(),1);var Eu=16*1024,ns=new WeakMap;function os(r){let e=r,t=ns.get(e);return t||(t=new bo(r),ns.set(e,t)),t}var bo=class{id;graph;buffer;capacityByteLength;nextByteOffset=0;slots=new Map;views=new Map;constructor(e,t="gpu-value-arena",n=Eu){if(this.id=t,this.graph=e,!Number.isSafeInteger(n)||n<=0||n%4!==0)throw new Error(`${this.id} capacityByteLength must be a positive multiple of 4`);this.capacityByteLength=n,this.buffer=e.createTransientBuffer({id:`${this.id}-buffer`,byteLength:n,usage:Wr.Buffer.STORAGE|Wr.Buffer.COPY_SRC|Wr.Buffer.COPY_DST})}allocate(e,t){if(!e)throw new Error(`${this.id} slot id must not be empty`);if(this.slots.has(e))throw new Error(`${this.id} slot "${e}" already exists`);if(!["float32","uint32","sint32"].includes(t))throw new Error(`${this.id} unsupported slot format ${t}`);if(this.nextByteOffset+4>this.capacityByteLength)throw new Error(`${this.id} capacity exceeded while allocating "${e}"`);let n=Object.freeze({id:e,format:t,byteOffset:this.nextByteOffset});return this.nextByteOffset+=4,this.slots.set(e,n),this.views.set(e,new Ge(this.buffer,{format:t,length:1,byteOffset:n.byteOffset,byteStride:4,rowByteLength:4})),n}get(e){return this.slots.get(e)}getSlots(){return Object.freeze([...this.slots.values()])}getView(e){let t=this.views.get(e.id);if(!t)throw new Error(`${this.id} does not contain slot "${e.id}"`);return t}get byteLength(){return this.nextByteOffset}get size(){return this.slots.size}get availableByteLength(){return this.capacityByteLength-this.nextByteOffset}};var xo=class{id;format;arena;slot;constructor(e,t){this.id=t.id,this.format=t.format,this.arena=e,this.slot=t}get byteOffset(){return this.slot.byteOffset}get wordOffset(){return this.slot.byteOffset>>>2}get view(){return this.arena.getView(this.slot)}};function wo(r,e,t){let n=os(r);return new xo(n,n.allocate(e,t))}function is(r){switch(r){case"float32":return"f32";case"uint32":return"u32";case"sint32":return"i32"}}function Ee(r,e="gpuValues"){let t=`${e}[${r.wordOffset}u]`;switch(r.format){case"float32":return`bitcast<f32>(${t})`;case"uint32":return t;case"sint32":return`bitcast<i32>(${t})`}}function it(r,e,t="gpuValues"){let n=`${t}[${r.wordOffset}u]`;switch(r.format){case"float32":return`${n} = bitcast<u32>(${e});`;case"uint32":return`${n} = ${e};`;case"sint32":return`${n} = bitcast<u32>(${e});`}}function pe(r,e,t="gpuValues"){return`@group(${r}) @binding(${e}) var<storage, read_write> ${t}: array<u32>;`}var fr=class{id;active;workgroups;dispatchBuffer;constructor(e,t){if(this.id=t.id,this.active=t.active,this.workgroups=t.workgroups,t.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);this.dispatchBuffer=e.createTransientBuffer({id:`${this.id}-dispatch`,byteLength:12,usage:Hr.Buffer.STORAGE|Hr.Buffer.INDIRECT|Hr.Buffer.COPY_SRC})}getUpdateCommandNodes(e,t=`${this.id}-update`){if(this.active.arena.graph!==e)throw new Error(`${this.id} active scalar must belong to target graph`);let n=this.active.arena.buffer,[o,i,s]=this.workgroups,a=`${pe(0,0)}
197
197
  @group(0) @binding(1) var<storage, read_write> dispatch: array<u32>;
198
198
  @compute @workgroup_size(1)
199
199
  fn main() {
200
- let enabled = ${Se(this.active)} != 0u;
201
- dispatch[0] = select(0u, ${i}u, enabled);
202
- dispatch[1] = ${o}u;
200
+ let enabled = ${Ee(this.active)} != 0u;
201
+ dispatch[0] = select(0u, ${o}u, enabled);
202
+ dispatch[1] = ${i}u;
203
203
  dispatch[2] = ${s}u;
204
- }`;return[N({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:n,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let c=new _(u,{id:t,source:a,shaderLayout:{bindings:[{name:"gpuValues",type:"read-only-storage",group:0,location:0},{name:"dispatch",type:"storage",group:0,location:1}]}});return{encode:({computePass:f,getBuffer:d})=>{let l={gpuValues:d(n),dispatch:d(this.dispatchBuffer)};c.dispatch(f,{bindings:l,x:1,y:1,z:1})},destroy:()=>c.destroy()}}})]}get condition(){return{id:`${this.id}-active`,source:"gpu",mode:"indirect",buffer:this.dispatchBuffer}}};function Nr(r,e,t){return e.flatMap(n=>{let i=Ar(n);if(n.type!=="compute"||n.condition||!i)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let o=new ar(r,{id:`${n.id}-gate`,active:t,workgroups:i});return[...o.getUpdateCommandNodes(r).map(s=>z(s,[1,1,1])),{...n,condition:o.condition}]})}var zr=class{id;operation;left;right;output;constructor(e){this.id=e.id??`gpu-scalar-${e.operation}`,this.operation=e.operation,this.left=e.left,this.right=e.right,this.output=e.output,hu(this)}getCommandNodes(e){let t=this.left.arena;if(this.right&&this.right.arena!==t)throw new Error(`${this.id} operands must belong to the same GPUValueArena`);if(this.output.arena!==t)throw new Error(`${this.id} output must belong to the same GPUValueArena`);if(t.graph!==e)throw new Error(`${this.id} scalars must belong to the target graph`);let n=t.buffer,i=mu(this);return[z(N({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:o})=>{let s=new _(o,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{let c={gpuValues:u(n)};s.dispatch(a,{bindings:c,x:1,y:1,z:1})},destroy:()=>s.destroy()}}}),[1,1,1])]}};function hu(r){let e=r.operation==="copy"||r.operation==="sqrt",t=gu(r.operation);if(!e&&!r.right)throw new Error(`${r.id} ${r.operation} requires a right operand`);if(e&&r.right)throw new Error(`${r.id} ${r.operation} does not accept a right operand`);if(r.right&&r.right.format!==r.left.format)throw new Error(`${r.id} input scalar formats must match`);if(r.operation==="sqrt"&&r.left.format!=="float32")throw new Error(`${r.id} sqrt currently requires float32 input`);if(t){if(r.output.format!=="uint32")throw new Error(`${r.id} comparison output must be uint32`)}else if(r.output.format!==r.left.format)throw new Error(`${r.id} arithmetic output format must match input format`)}function mu(r){let e=Se(r.left),t=r.right?Se(r.right):void 0,n=pu(r.operation,e,t);return`${me(0,0)}
205
- @compute @workgroup_size(1) fn main(){${ot(r.output,n)}}`}function pu(r,e,t){switch(r){case"copy":return e;case"add":return`(${e} + ${t})`;case"subtract":return`(${e} - ${t})`;case"multiply":return`(${e} * ${t})`;case"divide":return`(${e} / ${t})`;case"sqrt":return`sqrt(${e})`;case"min":return`min(${e}, ${t})`;case"max":return`max(${e}, ${t})`;case"equal":return`select(0u,1u,${e} == ${t})`;case"not-equal":return`select(0u,1u,${e} != ${t})`;case"less-than":return`select(0u,1u,${e} < ${t})`;case"less-than-or-equal":return`select(0u,1u,${e} <= ${t})`;case"greater-than":return`select(0u,1u,${e} > ${t})`;case"greater-than-or-equal":return`select(0u,1u,${e} >= ${t})`}}function gu(r){return["equal","not-equal","less-than","less-than-or-equal","greater-than","greater-than-or-equal"].includes(r)}var It=class{props;id;constructor(e){this.props=e,this.id=e.id??`${e.output.id}-literal`}getCommandNodes(e){let{output:t,value:n}=this.props;if(t.arena.graph!==e)throw new Error(`${this.id} output must belong to target graph`);let i=t.format==="float32"?`f32(${n})`:t.format==="uint32"?`${n}u`:`${n}i`,o=`
206
- ${me(0,0)}
204
+ }`;return[j({id:t,workload:{operation:"GPUScalarDispatchGate",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:4,writeByteLength:12},resources:[{buffer:n,usage:"storage-read"},{buffer:this.dispatchBuffer,usage:"storage-write"}],compile:({device:u})=>{let c=new F(u,{id:t,source:a,shaderLayout:{bindings:[{name:"gpuValues",type:"read-only-storage",group:0,location:0},{name:"dispatch",type:"storage",group:0,location:1}]}});return{encode:({computePass:d,getBuffer:f})=>{let l={gpuValues:f(n),dispatch:f(this.dispatchBuffer)};c.dispatch(d,{bindings:l,x:1,y:1,z:1})},destroy:()=>c.destroy()}}})]}get condition(){return{id:`${this.id}-active`,source:"gpu",mode:"indirect",buffer:this.dispatchBuffer}}};function qr(r,e,t){return e.flatMap(n=>{let o=Vr(n);if(n.type!=="compute"||n.condition||!o)throw new Error("Gated primitives must expose unconditional compute nodes with exact dispatch geometry");let i=new fr(r,{id:`${n.id}-gate`,active:t,workgroups:o});return[...i.getUpdateCommandNodes(r).map(s=>W(s,[1,1,1])),{...n,condition:i.condition}]})}var Yr=class{id;operation;left;right;output;constructor(e){this.id=e.id??`gpu-scalar-${e.operation}`,this.operation=e.operation,this.left=e.left,this.right=e.right,this.output=e.output,Pu(this)}getCommandNodes(e){let t=this.left.arena;if(this.right&&this.right.arena!==t)throw new Error(`${this.id} operands must belong to the same GPUValueArena`);if(this.output.arena!==t)throw new Error(`${this.id} output must belong to the same GPUValueArena`);if(t.graph!==e)throw new Error(`${this.id} scalars must belong to the target graph`);let n=t.buffer,o=Cu(this);return[W(j({id:this.id,workload:{operation:"GPUScalarCompute",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:this.right?8:4,writeByteLength:4},resources:[{buffer:n,usage:"storage-write"}],compile:({device:i})=>{let s=new F(i,{id:this.id,source:o,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:a,getBuffer:u})=>{let c={gpuValues:u(n)};s.dispatch(a,{bindings:c,x:1,y:1,z:1})},destroy:()=>s.destroy()}}}),[1,1,1])]}};function Pu(r){let e=r.operation==="copy"||r.operation==="sqrt",t=Bu(r.operation);if(!e&&!r.right)throw new Error(`${r.id} ${r.operation} requires a right operand`);if(e&&r.right)throw new Error(`${r.id} ${r.operation} does not accept a right operand`);if(r.right&&r.right.format!==r.left.format)throw new Error(`${r.id} input scalar formats must match`);if(r.operation==="sqrt"&&r.left.format!=="float32")throw new Error(`${r.id} sqrt currently requires float32 input`);if(t){if(r.output.format!=="uint32")throw new Error(`${r.id} comparison output must be uint32`)}else if(r.output.format!==r.left.format)throw new Error(`${r.id} arithmetic output format must match input format`)}function Cu(r){let e=Ee(r.left),t=r.right?Ee(r.right):void 0,n=Lu(r.operation,e,t);return`${pe(0,0)}
205
+ @compute @workgroup_size(1) fn main(){${it(r.output,n)}}`}function Lu(r,e,t){switch(r){case"copy":return e;case"add":return`(${e} + ${t})`;case"subtract":return`(${e} - ${t})`;case"multiply":return`(${e} * ${t})`;case"divide":return`(${e} / ${t})`;case"sqrt":return`sqrt(${e})`;case"min":return`min(${e}, ${t})`;case"max":return`max(${e}, ${t})`;case"equal":return`select(0u,1u,${e} == ${t})`;case"not-equal":return`select(0u,1u,${e} != ${t})`;case"less-than":return`select(0u,1u,${e} < ${t})`;case"less-than-or-equal":return`select(0u,1u,${e} <= ${t})`;case"greater-than":return`select(0u,1u,${e} > ${t})`;case"greater-than-or-equal":return`select(0u,1u,${e} >= ${t})`}}function Bu(r){return["equal","not-equal","less-than","less-than-or-equal","greater-than","greater-than-or-equal"].includes(r)}var At=class{props;id;constructor(e){this.props=e,this.id=e.id??`${e.output.id}-literal`}getCommandNodes(e){let{output:t,value:n}=this.props;if(t.arena.graph!==e)throw new Error(`${this.id} output must belong to target graph`);let o=t.format==="float32"?`f32(${n})`:t.format==="uint32"?`${n}u`:`${n}i`,i=`
206
+ ${pe(0,0)}
207
207
 
208
208
  @compute @workgroup_size(1)
209
209
  fn main() {
210
- ${ot(t,i)}
210
+ ${it(t,o)}
211
211
  }
212
- `,s=t.arena.buffer;return[z(N({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:s,usage:"storage-write"}],compile:({device:a})=>{let u=new _(a,{id:this.id,source:o,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:f})=>{let d={gpuValues:f(s)};u.dispatch(c,{bindings:d,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};var Wr=256,jr=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,n]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let i of Y(n))mt(i,["float32"],`${this.id} ${t}`);if(e.input.length!==e.addend.length||e.input.length!==e.output.length)throw new Error(`${this.id} vector lengths must match`)}getCommandNodes(e){let{input:t,scale:n,addend:i,output:o,gate:s}=this.props;if(t instanceof D||i instanceof D||o instanceof D)return ue(e,[t,i,o]).flatMap(([h,m,p],y)=>new r({id:`${this.id}-chunk-${y}`,input:h,addend:m,output:p,scale:n,gate:s}).getCommandNodes(e));if([t,i,o].some(h=>h.buffer.graph!==e)||n.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(o.length===0)return[];let a=n.arena.buffer,u=ze("GPUVectorScalarMADD",o.length,Wr,e.device.limits.maxComputeWorkgroupsPerDimension),c=t===o?"outputValues":"inputValues",f=i===o?"outputValues":"addendValues",d=`
213
- const LENGTH: u32 = ${o.length}u;
212
+ `,s=t.arena.buffer;return[W(j({id:this.id,workload:{operation:"GPUScalarLiteral",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:0,writeByteLength:4},resources:[{buffer:s,usage:"storage-write"}],compile:({device:a})=>{let u=new F(a,{id:this.id,source:i,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let f={gpuValues:d(s)};u.dispatch(c,{bindings:f,x:1,y:1,z:1})},destroy:()=>u.destroy()}}}),[1,1,1])]}};var Xr=256,Kr=class r{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-vector-scalar-madd";for(let[t,n]of Object.entries({input:e.input,addend:e.addend,output:e.output}))for(let o of Y(n))pt(o,["float32"],`${this.id} ${t}`);if(e.input.length!==e.addend.length||e.input.length!==e.output.length)throw new Error(`${this.id} vector lengths must match`)}getCommandNodes(e){let{input:t,scale:n,addend:o,output:i,gate:s}=this.props;if(t instanceof G||o instanceof G||i instanceof G)return ce(e,[t,o,i]).flatMap(([h,m,g],y)=>new r({id:`${this.id}-chunk-${y}`,input:h,addend:m,output:g,scale:n,gate:s}).getCommandNodes(e));if([t,o,i].some(h=>h.buffer.graph!==e)||n.arena.graph!==e)throw new Error(`${this.id} resources must belong to target graph`);if(i.length===0)return[];let a=n.arena.buffer,u=je("GPUVectorScalarMADD",i.length,Xr,e.device.limits.maxComputeWorkgroupsPerDimension),c=t===i?"outputValues":"inputValues",d=o===i?"outputValues":"addendValues",f=`
213
+ const LENGTH: u32 = ${i.length}u;
214
214
  const I: u32 = ${L(t)}u;
215
- const A: u32 = ${L(i)}u;
216
- const O: u32 = ${L(o)}u;
215
+ const A: u32 = ${L(o)}u;
216
+ const O: u32 = ${L(i)}u;
217
217
 
218
- ${t===o?"":"@group(0) @binding(0) var<storage, read> inputValues: array<f32>;"}
219
- ${i===o?"":"@group(0) @binding(1) var<storage, read> addendValues: array<f32>;"}
218
+ ${t===i?"":"@group(0) @binding(0) var<storage, read> inputValues: array<f32>;"}
219
+ ${o===i?"":"@group(0) @binding(1) var<storage, read> addendValues: array<f32>;"}
220
220
  @group(0) @binding(2) var<storage, read_write> outputValues: array<f32>;
221
- ${me(0,3)}
221
+ ${pe(0,3)}
222
222
 
223
- @compute @workgroup_size(${Wr})
223
+ @compute @workgroup_size(${Xr})
224
224
  fn main(
225
225
  @builtin(workgroup_id) workgroupId: vec3u,
226
226
  @builtin(local_invocation_index) localInvocationIndex: u32
227
227
  ) {
228
- ${he(u,Wr)}
228
+ ${me(u,Xr)}
229
229
  if (index >= LENGTH) {
230
230
  return;
231
231
  }
232
232
 
233
233
  let x = ${c}[I + index];
234
- let y = ${f}[A + index];
235
- outputValues[O + index] = ${Se(n)} * x + y;
234
+ let y = ${d}[A + index];
235
+ outputValues[O + index] = ${Ee(n)} * x + y;
236
236
  }
237
- `,l=[z(N({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*Wr,readByteLength:t.length*8+4,writeByteLength:o.length*4},resources:[...t===o?[]:[{buffer:t,usage:"storage-read"}],...i===o?[]:[{buffer:i,usage:"storage-read"}],{buffer:o,usage:t===o||i===o?"storage-read-write":"storage-write"},{buffer:a,usage:"storage-read"}],compile:({device:h})=>{let m=new _(h,{id:this.id,source:d,shaderLayout:{bindings:[...t===o?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...i===o?[]:[{name:"addendValues",type:"read-only-storage",group:0,location:1}],{name:"outputValues",type:"storage",group:0,location:2},{name:"gpuValues",type:"read-only-storage",group:0,location:3}]}});return{encode:({computePass:p,getBuffer:y})=>{let g={...t===o?{}:{inputValues:$(t,y)},...i===o?{}:{addendValues:$(i,y)},outputValues:$(o,y),gpuValues:y(a)};m.dispatch(p,{bindings:g,x:u.x,y:u.y,z:u.z})},destroy:()=>m.destroy()}}}),[u.x,u.y,u.z])];return s?Nr(e,l,s.active):l}};function go(r,e,t,n){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<0||n<0||t+n>e.length)throw new Error("Graph range must fit the source");let i=[],o=e instanceof D?e.chunks:[{offset:0,length:e.length,data:e}],s=0,a=o.length;for(;s<a;){let u=Math.floor((s+a)/2);o[u].offset+o[u].length<=t?s=u+1:a=u}for(let u=s;u<o.length&&o[u].offset<t+n;u++){let{data:c,offset:f}=o[u],d=Math.max(t,f),l=Math.min(t+n,f+c.length);d<l&&i.push(d===f&&l===f+c.length?c:r.createDataView(c.buffer,{format:c.format,length:l-d,byteOffset:c.byteOffset+(d-f)*c.byteStride,byteStride:c.byteStride,rowByteLength:c.rowByteLength}))}return new D({id:`graph-range-${t}-${n}`,name:`graph-range-${t}-${n}`,stride:e instanceof D?e.stride:U(e.format).components*(U(e.format).listSize??1),format:e.format,length:n,valueLength:n*(U(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:i})}function Qi(r,e,t){if([...e,...t].some(a=>a.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let n=e.flatMap(Y),i=t.flatMap(Y);for(let a of[...n,...i])if(a.buffer.graph!==r)throw new Error("Views must belong to the target graph");let o=new Set(n.map(a=>a.buffer)),s=new Map;for(let a of i){if(o.has(a.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!a.length)continue;let u=s.get(a.buffer)??[];u.push(a),s.set(a.buffer,u)}for(let a of s.values()){a.sort((c,f)=>c.byteOffset-f.byteOffset);let u=0;for(let c of a){if(c.byteOffset<u)throw new Error("Writable chunks must not overlap");u=c.byteOffset+(c.length-1)*c.byteStride+c.rowByteLength}}}function $t(r,e){if(!Number.isSafeInteger(r)||r<1||r>4294967295||!Number.isSafeInteger(e)||e<1)throw new Error("Invalid chunk dispatch");let t=Math.min(r,e),n=Math.min(Math.ceil(r/t),e),i=Math.ceil(r/t/n);if(i>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:n,z:i}}function Hr(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,i]of t)if(sr(i).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let n=e.dispatch.x*e.dispatch.y*e.dispatch.z;return z(N({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:n,maximumInvocationCount:n*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(i=>({buffer:i,usage:"storage-read"})),...Object.values(e.outputs).map(i=>({buffer:i,usage:"storage-read-write"}))],compile:({device:i})=>{let o=new _(i,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([s],a)=>({name:s,group:0,location:a,type:a<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:s,getBuffer:a})=>{let u={};for(let[c,f]of t)u[c]=$(f,a);o.dispatch(s,{bindings:u,x:e.dispatch.x,y:e.dispatch.y,z:e.dispatch.z})},destroy:()=>o.destroy()}}}),[e.dispatch.x,e.dispatch.y,e.dispatch.z])}var bt=256;function yu(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/bt),e.push(r);while(r>1);return e}function Zi(r,e){let t=[],n=e.input,i=e.inputB===n?void 0:e.inputB,o=e.inputB===n;for(let[s,a]of yu(n.length).entries()){let u=a>1?H(r,`${e.id}-partials-${s}`,"float32",a):void 0;t.push(bu(r,{id:`${e.id}-level-${s}`,input:n,inputB:i,square:o,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(n=u),i=void 0,o=!1}return t}function bu(r,e){let t=e.output?.length??1,n=$t(t,r.device.limits.maxComputeWorkgroupsPerDimension),i=e.finalScalar?.arena.buffer,o=e.inputB?2:1,s=Ut(r.device,{requiresSubgroupId:!0})==="subgroups",a=xu(e,n,s);return z(N({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:n.x*n.y*n.z,maximumInvocationCount:n.x*n.y*n.z*bt,readByteLength:e.input.length*4*(e.inputB?2:1),writeByteLength:t*4},resources:[{buffer:e.input,usage:"storage-read"},...e.inputB?[{buffer:e.inputB,usage:"storage-read"}]:[],...e.output?[{buffer:e.output,usage:"storage-write"}]:[],...i?[{buffer:i,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let c=new _(u,{id:e.id,source:a,shaderLayout:{bindings:[{name:"inputValues",type:"read-only-storage",group:0,location:0},...e.inputB?[{name:"inputBValues",type:"read-only-storage",group:0,location:1}]:[],{name:e.output?"outputValues":"gpuValues",type:"storage",group:0,location:o}]}});return{encode:({computePass:f,getBuffer:d})=>{let l={inputValues:$(e.input,d)};e.inputB&&(l.inputBValues=$(e.inputB,d)),e.output&&(l.outputValues=$(e.output,d)),i&&(l.gpuValues=d(i)),c.dispatch(f,{bindings:l,...n})},destroy:()=>c.destroy()}}}),[n.x,n.y,n.z])}function xu(r,e,t){let n=r.inputB?2:1,i=`inputValues[${L(r.input)}u + index]`,o=r.inputB?`${i} * inputBValues[${L(r.inputB)}u + index]`:r.square?`${i} * ${i}`:i,s=r.output?`outputValues[${L(r.output)}u + groupIndex] = total;`:ot(r.finalScalar,r.accumulate?`${Se(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
237
+ `,l=[W(j({id:this.id,workload:{operation:"GPUVectorScalarMADD",commandCount:1,maximumWorkgroupCount:u.x*u.y*u.z,maximumInvocationCount:u.x*u.y*u.z*Xr,readByteLength:t.length*8+4,writeByteLength:i.length*4},resources:[...t===i?[]:[{buffer:t,usage:"storage-read"}],...o===i?[]:[{buffer:o,usage:"storage-read"}],{buffer:i,usage:t===i||o===i?"storage-read-write":"storage-write"},{buffer:a,usage:"storage-read"}],compile:({device:h})=>{let m=new F(h,{id:this.id,source:f,shaderLayout:{bindings:[...t===i?[]:[{name:"inputValues",type:"read-only-storage",group:0,location:0}],...o===i?[]:[{name:"addendValues",type:"read-only-storage",group:0,location:1}],{name:"outputValues",type:"storage",group:0,location:2},{name:"gpuValues",type:"read-only-storage",group:0,location:3}]}});return{encode:({computePass:g,getBuffer:y})=>{let p={...t===i?{}:{inputValues:$(t,y)},...o===i?{}:{addendValues:$(o,y)},outputValues:$(i,y),gpuValues:y(a)};m.dispatch(g,{bindings:p,x:u.x,y:u.y,z:u.z})},destroy:()=>m.destroy()}}}),[u.x,u.y,u.z])];return s?qr(e,l,s.active):l}};function To(r,e,t,n){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<0||n<0||t+n>e.length)throw new Error("Graph range must fit the source");let o=[],i=e instanceof G?e.chunks:[{offset:0,length:e.length,data:e}],s=0,a=i.length;for(;s<a;){let u=Math.floor((s+a)/2);i[u].offset+i[u].length<=t?s=u+1:a=u}for(let u=s;u<i.length&&i[u].offset<t+n;u++){let{data:c,offset:d}=i[u],f=Math.max(t,d),l=Math.min(t+n,d+c.length);f<l&&o.push(f===d&&l===d+c.length?c:r.createDataView(c.buffer,{format:c.format,length:l-f,byteOffset:c.byteOffset+(f-d)*c.byteStride,byteStride:c.byteStride,rowByteLength:c.rowByteLength}))}return new G({id:`graph-range-${t}-${n}`,name:`graph-range-${t}-${n}`,stride:e instanceof G?e.stride:I(e.format).components*(I(e.format).listSize??1),format:e.format,length:n,valueLength:n*(I(e.format).listSize??1),byteStride:e.byteStride,rowByteLength:e.rowByteLength,data:o})}function ss(r,e,t){if([...e,...t].some(a=>a.length>4294967295))throw new Error("Logical lengths must fit uint32 addressing");let n=e.flatMap(Y),o=t.flatMap(Y);for(let a of[...n,...o])if(a.buffer.graph!==r)throw new Error("Views must belong to the target graph");let i=new Set(n.map(a=>a.buffer)),s=new Map;for(let a of o){if(i.has(a.buffer))throw new Error("Outputs must use separate buffers from inputs");if(!a.length)continue;let u=s.get(a.buffer)??[];u.push(a),s.set(a.buffer,u)}for(let a of s.values()){a.sort((c,d)=>c.byteOffset-d.byteOffset);let u=0;for(let c of a){if(c.byteOffset<u)throw new Error("Writable chunks must not overlap");u=c.byteOffset+(c.length-1)*c.byteStride+c.rowByteLength}}}function _t(r,e){if(!Number.isSafeInteger(r)||r<1||r>4294967295||!Number.isSafeInteger(e)||e<1)throw new Error("Invalid chunk dispatch");let t=Math.min(r,e),n=Math.min(Math.ceil(r/t),e),o=Math.ceil(r/t/n);if(o>e)throw new Error("Chunk operation exceeds the 3D dispatch limit");return{x:t,y:n,z:o}}function Qr(r,e){let t=[...Object.entries(e.inputs??{}),...Object.entries(e.outputs)];for(let[,o]of t)if(dr(o).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let n=e.dispatch.x*e.dispatch.y*e.dispatch.z;return W(j({id:e.id,workload:{commandCount:1,maximumWorkgroupCount:n,maximumInvocationCount:n*(e.workgroupSize??256)},resources:[...Object.values(e.inputs??{}).map(o=>({buffer:o,usage:"storage-read"})),...Object.values(e.outputs).map(o=>({buffer:o,usage:"storage-read-write"}))],compile:({device:o})=>{let i=new F(o,{id:e.id,source:e.source,shaderLayout:{bindings:t.map(([s],a)=>({name:s,group:0,location:a,type:a<Object.keys(e.inputs??{}).length?"read-only-storage":"storage"}))}});return{encode:({computePass:s,getBuffer:a})=>{let u={};for(let[c,d]of t)u[c]=$(d,a);i.dispatch(s,{bindings:u,x:e.dispatch.x,y:e.dispatch.y,z:e.dispatch.z})},destroy:()=>i.destroy()}}}),[e.dispatch.x,e.dispatch.y,e.dispatch.z])}var xt=256;function Ou(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("reduction length must be positive");let e=[];do r=Math.ceil(r/xt),e.push(r);while(r>1);return e}function as(r,e){let t=[],n=e.input,o=e.inputB===n?void 0:e.inputB,i=e.inputB===n;for(let[s,a]of Ou(n.length).entries()){let u=a>1?q(r,`${e.id}-partials-${s}`,"float32",a):void 0;t.push(Gu(r,{id:`${e.id}-level-${s}`,input:n,inputB:o,square:i,output:u,finalScalar:u?void 0:e.output,accumulate:e.accumulate})),u&&(n=u),o=void 0,i=!1}return t}function Gu(r,e){let t=e.output?.length??1,n=_t(t,r.device.limits.maxComputeWorkgroupsPerDimension),o=e.finalScalar?.arena.buffer,i=e.inputB?2:1,s=kt(r.device,{requiresSubgroupId:!0})==="subgroups",a=Du(e,n,s);return W(j({id:e.id,workload:{operation:"GPUDotProductScalar",commandCount:1,maximumWorkgroupCount:n.x*n.y*n.z,maximumInvocationCount:n.x*n.y*n.z*xt,readByteLength:e.input.length*4*(e.inputB?2:1),writeByteLength:t*4},resources:[{buffer:e.input,usage:"storage-read"},...e.inputB?[{buffer:e.inputB,usage:"storage-read"}]:[],...e.output?[{buffer:e.output,usage:"storage-write"}]:[],...o?[{buffer:o,usage:"storage-read-write"}]:[]],compile:({device:u})=>{let c=new F(u,{id:e.id,source:a,shaderLayout:{bindings:[{name:"inputValues",type:"read-only-storage",group:0,location:0},...e.inputB?[{name:"inputBValues",type:"read-only-storage",group:0,location:1}]:[],{name:e.output?"outputValues":"gpuValues",type:"storage",group:0,location:i}]}});return{encode:({computePass:d,getBuffer:f})=>{let l={inputValues:$(e.input,f)};e.inputB&&(l.inputBValues=$(e.inputB,f)),e.output&&(l.outputValues=$(e.output,f)),o&&(l.gpuValues=f(o)),c.dispatch(d,{bindings:l,...n})},destroy:()=>c.destroy()}}}),[n.x,n.y,n.z])}function Du(r,e,t){let n=r.inputB?2:1,o=`inputValues[${L(r.input)}u + index]`,i=r.inputB?`${o} * inputBValues[${L(r.inputB)}u + index]`:r.square?`${o} * ${o}`:o,s=r.output?`outputValues[${L(r.output)}u + groupIndex] = total;`:it(r.finalScalar,r.accumulate?`${Ee(r.finalScalar)} + total`:"total");return`${t?`enable subgroups;
238
238
  requires subgroup_id;
239
239
  `:""}
240
240
  @group(0) @binding(0) var<storage, read> inputValues: array<f32>;
241
241
  ${r.inputB?"@group(0) @binding(1) var<storage, read> inputBValues: array<f32>;":""}
242
- ${r.output?`@group(0) @binding(${n}) var<storage, read_write> outputValues: array<f32>;`:me(0,n)}
243
- ${t?Tu:wu}
244
- @compute @workgroup_size(${bt})
242
+ ${r.output?`@group(0) @binding(${n}) var<storage, read_write> outputValues: array<f32>;`:pe(0,n)}
243
+ ${t?Uu:Iu}
244
+ @compute @workgroup_size(${xt})
245
245
  fn main(
246
246
  @builtin(local_invocation_index) lane: u32,
247
247
  @builtin(workgroup_id) workgroupId: vec3u${t?`,
@@ -251,35 +251,35 @@ fn main(
251
251
  ) {
252
252
  let groupIndex = workgroupId.x + ${e.x}u * (workgroupId.y + ${e.y}u * workgroupId.z);
253
253
  if (groupIndex >= ${r.output?.length??1}u) { return; }
254
- let index = groupIndex * ${bt}u + lane;
254
+ let index = groupIndex * ${xt}u + lane;
255
255
  var value = 0.0;
256
- if (index < ${r.input.length}u) { value = ${o}; }
256
+ if (index < ${r.input.length}u) { value = ${i}; }
257
257
  let total = reduceValue(value, lane${t?", subgroupInvocationId, subgroupSize, subgroupId":""});
258
258
  if (lane == 0u) { ${s} }
259
- }`}var wu=`
260
- var<workgroup> reductionScratch: array<f32, ${bt}>;
259
+ }`}var Iu=`
260
+ var<workgroup> reductionScratch: array<f32, ${xt}>;
261
261
  fn reduceValue(value: f32, lane: u32) -> f32 {
262
262
  reductionScratch[lane] = value;
263
263
  workgroupBarrier();
264
- for (var stride = ${bt/2}u; stride > 0u; stride /= 2u) {
264
+ for (var stride = ${xt/2}u; stride > 0u; stride /= 2u) {
265
265
  if (lane < stride) { reductionScratch[lane] += reductionScratch[lane + stride]; }
266
266
  workgroupBarrier();
267
267
  }
268
268
  return reductionScratch[0];
269
- }`,Tu=`
269
+ }`,Uu=`
270
270
  var<workgroup> subgroupTotals: array<f32, 64>;
271
271
  fn reduceValue(value: f32, lane: u32, subgroupInvocationId: u32, subgroupSize: u32, subgroupId: u32) -> f32 {
272
272
  let subtotal = subgroupAdd(value);
273
273
  if (subgroupInvocationId == 0u) { subgroupTotals[subgroupId] = subtotal; }
274
274
  workgroupBarrier();
275
- let subgroupCount = ${bt}u / subgroupSize;
275
+ let subgroupCount = ${xt}u / subgroupSize;
276
276
  for (var stride = subgroupCount / 2u; stride > 0u; stride /= 2u) {
277
277
  if (lane < stride) { subgroupTotals[lane] += subgroupTotals[lane + stride]; }
278
278
  workgroupBarrier();
279
279
  }
280
280
  return subgroupTotals[0];
281
- }`;var qr=class{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-dot-product-scalar";for(let t of[e.left,e.right])for(let n of Y(t))mt(n,["float32"],this.id);if(e.left.length!==e.right.length||e.left.length>4294967295)throw new Error(`${this.id} inputs must have equal uint32-addressable lengths`)}getCommandNodes(e){let{left:t,right:n,output:i,gate:o}=this.props;if(i.arena.graph!==e||o&&o.active.arena.graph!==e||[t,n].flatMap(Y).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let s=[],a=0;for(let u of ue(e,[t,n]))for(let c=0;c<u[0].length;){let f=Math.min(u[0].length-c,...u.map(h=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(h.byteOffset+c*4)%256)/4)));if(f<1)throw new Error("Dot product span must fit a storage binding");let d=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+c*4,length:f}),l=u[1]===u[0]?d:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+c*4,length:f});s.push(...Zi(e,{id:`${this.id}-chunk-${a}`,input:d,inputB:l,output:i,accumulate:a>0})),a++,c+=f}return a||s.push(...new It({id:this.id,output:i,value:0}).getCommandNodes(e)),o?Nr(e,s,o.active):s}};var Yr=256,kt=Uint32Array.BYTES_PER_ELEMENT,Xr=class{id;source;indices;output;wordsPerRow;constructor(e){this.id=e.id??"gpu-gather",this.source=e.source,this.indices=e.indices,this.output=e.output;for(let n of Y(this.indices))pt(n,`${this.id} indices`);for(let n of[this.source,this.output])for(let i of Y(n))Su(i,this.id,n===this.output);if(this.source.format!==this.output.format)throw new Error(`${this.id} source and output must use the same format`);if(this.output.length<this.indices.length)throw new Error(`${this.id} output must contain at least indices.length rows`);let t=new Set([...Y(this.source).map(n=>n.buffer),...Y(this.indices).map(n=>n.buffer)]);if(Y(this.output).some(n=>t.has(n.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=U(this.source.format).byteLength/kt}getCommandNodes(e){return vu(e,this)}};function vu(r,e,t=0,n="GPUGather"){let i=[];for(let c of[e.source,e.indices,e.output])for(let f of Y(c))if(f.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return i;let o=Vi(r,e.output,e.indices.length),s=ue(r,[e.indices,o]),a=Ae(Y(e.source)).filter(c=>c.length),u=a.length?a:[void 0];for(let[c,[f,d]]of s.entries()){let l=ze(n,f.length,Yr,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[h,m]of u.entries()){let p=m?.data;for(let w of[d,...p?[p,f]:[]])if(sr(w).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let y=s.length===1&&u.length===1?e.id:`${e.id}-span-${c}-source-${h}`,g=Eu({source:p,sourceOffset:m?.offset??0,indices:f,output:d,wordsPerRow:e.wordsPerRow,initialize:h===0,invalidValue:t,dispatchLayout:l});i.push(z(N({id:y,workload:{operation:n,commandCount:1,maximumWorkgroupCount:l.x*l.y*l.z,maximumInvocationCount:l.x*l.y*l.z*Yr,readByteLength:p?f.length*(kt+p.rowByteLength):0,writeByteLength:f.length*d.rowByteLength},resources:[...p?[{buffer:p,usage:"storage-read"},{buffer:f,usage:"storage-read"}]:[],{buffer:d,usage:"storage-write"}],compile:({device:w})=>{let S=new _(w,{id:y,source:g,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...p?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:v,getBuffer:T})=>{let b={outputWords:$(d,T)};p&&(b.sourceWords=$(p,T),b.indices=$(f,T)),S.dispatch(v,{bindings:b,x:l.x,y:l.y,z:l.z})},destroy:()=>S.destroy()}}}),[l.x,l.y,l.z]))}}return i}function Su(r,e,t){if(Je(r.format)||et(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let n=U(r.format);if((t?r.byteStride!==n.byteLength:r.byteStride<n.byteLength||r.byteStride%kt!==0)||r.rowByteLength!==n.byteLength||r.byteOffset%kt!==0||r.rowByteLength%kt!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function Eu(r){let{source:e,indices:t,output:n,wordsPerRow:i,initialize:o,invalidValue:s,dispatchLayout:a}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
282
- const WORDS_PER_ROW: u32 = ${i}u;
281
+ }`;var Zr=class{props;id;constructor(e){this.props=e,this.id=e.id??"gpu-dot-product-scalar";for(let t of[e.left,e.right])for(let n of Y(t))pt(n,["float32"],this.id);if(e.left.length!==e.right.length||e.left.length>4294967295)throw new Error(`${this.id} inputs must have equal uint32-addressable lengths`)}getCommandNodes(e){let{left:t,right:n,output:o,gate:i}=this.props;if(o.arena.graph!==e||i&&i.active.arena.graph!==e||[t,n].flatMap(Y).some(u=>u.buffer.graph!==e))throw new Error(`${this.id} resources must belong to target graph`);let s=[],a=0;for(let u of ce(e,[t,n]))for(let c=0;c<u[0].length;){let d=Math.min(u[0].length-c,...u.map(h=>Math.floor((e.device.limits.maxStorageBufferBindingSize-(h.byteOffset+c*4)%256)/4)));if(d<1)throw new Error("Dot product span must fit a storage binding");let f=e.createDataView(u[0].buffer,{format:"float32",byteOffset:u[0].byteOffset+c*4,length:d}),l=u[1]===u[0]?f:e.createDataView(u[1].buffer,{format:"float32",byteOffset:u[1].byteOffset+c*4,length:d});s.push(...as(e,{id:`${this.id}-chunk-${a}`,input:f,inputB:l,output:o,accumulate:a>0})),a++,c+=d}return a||s.push(...new At({id:this.id,output:o,value:0}).getCommandNodes(e)),i?qr(e,s,i.active):s}};var Jr=256,Ft=Uint32Array.BYTES_PER_ELEMENT,en=class{id;source;indices;output;wordsPerRow;constructor(e){this.id=e.id??"gpu-gather",this.source=e.source,this.indices=e.indices,this.output=e.output;for(let n of Y(this.indices))gt(n,`${this.id} indices`);for(let n of[this.source,this.output])for(let o of Y(n))ku(o,this.id,n===this.output);if(this.source.format!==this.output.format)throw new Error(`${this.id} source and output must use the same format`);if(this.output.length<this.indices.length)throw new Error(`${this.id} output must contain at least indices.length rows`);let t=new Set([...Y(this.source).map(n=>n.buffer),...Y(this.indices).map(n=>n.buffer)]);if(Y(this.output).some(n=>t.has(n.buffer)))throw new Error(`${this.id} output must use a separate buffer`);this.wordsPerRow=I(this.source.format).byteLength/Ft}getCommandNodes(e){return $u(e,this)}};function $u(r,e,t=0,n="GPUGather"){let o=[];for(let c of[e.source,e.indices,e.output])for(let d of Y(c))if(d.buffer.graph!==r)throw new Error(`${e.id} views must belong to the target graph`);if(e.indices.length===0)return o;let i=Xi(r,e.output,e.indices.length),s=ce(r,[e.indices,i]),a=_e(Y(e.source)).filter(c=>c.length),u=a.length?a:[void 0];for(let[c,[d,f]]of s.entries()){let l=je(n,d.length,Jr,r.device.limits.maxComputeWorkgroupsPerDimension);for(let[h,m]of u.entries()){let g=m?.data;for(let w of[f,...g?[g,d]:[]])if(dr(w).size>r.device.limits.maxStorageBufferBindingSize)throw new Error("Active chunks must fit a storage binding");let y=s.length===1&&u.length===1?e.id:`${e.id}-span-${c}-source-${h}`,p=Au({source:g,sourceOffset:m?.offset??0,indices:d,output:f,wordsPerRow:e.wordsPerRow,initialize:h===0,invalidValue:t,dispatchLayout:l});o.push(W(j({id:y,workload:{operation:n,commandCount:1,maximumWorkgroupCount:l.x*l.y*l.z,maximumInvocationCount:l.x*l.y*l.z*Jr,readByteLength:g?d.length*(Ft+g.rowByteLength):0,writeByteLength:d.length*f.rowByteLength},resources:[...g?[{buffer:g,usage:"storage-read"},{buffer:d,usage:"storage-read"}]:[],{buffer:f,usage:"storage-write"}],compile:({device:w})=>{let S=new F(w,{id:y,source:p,shaderLayout:{bindings:[{name:"outputWords",type:"storage",group:0,location:0},...g?[{name:"sourceWords",type:"read-only-storage",group:0,location:1},{name:"indices",type:"read-only-storage",group:0,location:2}]:[]]}});return{encode:({computePass:v,getBuffer:T})=>{let b={outputWords:$(f,T)};g&&(b.sourceWords=$(g,T),b.indices=$(d,T)),S.dispatch(v,{bindings:b,x:l.x,y:l.y,z:l.z})},destroy:()=>S.destroy()}}}),[l.x,l.y,l.z]))}}return o}function ku(r,e,t){if(et(r.format)||tt(r.format))throw new Error(`${e} must use a fixed-width GPU data format`);let n=I(r.format);if((t?r.byteStride!==n.byteLength:r.byteStride<n.byteLength||r.byteStride%Ft!==0)||r.rowByteLength!==n.byteLength||r.byteOffset%Ft!==0||r.rowByteLength%Ft!==0)throw new Error(`${e} must be packed, uint32-aligned GPU data with 32-bit-word rows`)}function Au(r){let{source:e,indices:t,output:n,wordsPerRow:o,initialize:i,invalidValue:s,dispatchLayout:a}=r;return`const INDEX_COUNT: u32 = ${t.length}u;
282
+ const WORDS_PER_ROW: u32 = ${o}u;
283
283
  const OUTPUT_OFFSET: u32 = ${L(n)}u;
284
284
  @group(0) @binding(0) var<storage, read_write> outputWords: array<u32>;
285
285
  ${e?`
@@ -290,50 +290,50 @@ const INDEX_OFFSET: u32 = ${L(t)}u;
290
290
  @group(0) @binding(1) var<storage, read> sourceWords: array<u32>;
291
291
  @group(0) @binding(2) var<storage, read> indices: array<u32>;
292
292
  `:""}
293
- @compute @workgroup_size(${Yr})
293
+ @compute @workgroup_size(${Jr})
294
294
  fn main(
295
295
  @builtin(workgroup_id) workgroupId: vec3u,
296
296
  @builtin(local_invocation_index) localInvocationIndex: u32
297
297
  ) {
298
- ${he(a,Yr)}
298
+ ${me(a,Jr)}
299
299
  if (index >= INDEX_COUNT) { return; }
300
300
  let outputBase = OUTPUT_OFFSET + index * WORDS_PER_ROW;
301
301
  ${e?`
302
302
  let sourceIndex = indices[INDEX_OFFSET + index];
303
303
  if (sourceIndex >= SOURCE_ROW_OFFSET && sourceIndex - SOURCE_ROW_OFFSET < SOURCE_LENGTH) {
304
- let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${e.byteStride/kt}u;
304
+ let sourceBase = SOURCE_OFFSET + (sourceIndex - SOURCE_ROW_OFFSET) * ${e.byteStride/Ft}u;
305
305
  for (var word = 0u; word < WORDS_PER_ROW; word++) {
306
306
  outputWords[outputBase + word] = sourceWords[sourceBase + word];
307
307
  }
308
308
  return;
309
309
  }
310
310
  `:""}
311
- ${o?`
311
+ ${i?`
312
312
  for (var word = 0u; word < WORDS_PER_ROW; word++) {
313
313
  outputWords[outputBase + word] = ${s}u;
314
314
  }
315
315
  `:""}
316
- }`}function es(r){if(r.candidates.length===0)throw new Error("GPU strategy candidate list must not be empty");let e={device:r.device,workload:r.workload},t=r.candidates.filter(o=>o.isSupported?.(e)??!0);if(t.length===0)throw new Error("no supported GPU strategy candidate");if(r.preferredId){let o=t.find(s=>s.id===r.preferredId);if(!o)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return Ji(o,e)}let n=t[0],i=n.score(e);for(let o=1;o<t.length;o++){let s=t[o],a=s.score(e);a>i&&(n=s,i=a)}return Ji(n,e,i)}function Ji(r,e,t=r.score(e)){return Object.freeze({id:r.id,score:t,reason:r.reason(e),details:Object.freeze(r.createDetails(e))})}function ts(r,e,t){if(!Number.isSafeInteger(e.rows)||e.rows<0)throw new Error("SpMV rows must be non-negative");if(!Number.isSafeInteger(e.nonZeros)||e.nonZeros<0)throw new Error("SpMV nonZeros must be non-negative");let n=e.nonZeros/Math.max(1,e.rows),i=e.statistics?.maxNonZerosPerRow,o=e.statistics?.shortRowFraction,s=Ut(r,{requiresSubgroupId:!0})==="subgroups";return es({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>n<=8?100:n<=16?60:10,reason:()=>`average row length ${n.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>s,score:()=>n<=64&&(o===void 0||o<.9)?110:35,reason:()=>"subgroups available; medium CSR rows can reduce within a subgroup",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:128,workgroupsPerLongRow:1})},{id:"workgroup-row",score:()=>n>32&&(i===void 0||i<=2048)?100:50,reason:()=>`average row length ${n.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>i!==void 0&&i>2048||n>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var Kr=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,n]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let i of Y(n))mt(i,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(n.length>4294967295)throw new Error("SpMV logical lengths must fit in uint32")}if(e.rowOffsets.length!==e.output.length+1)throw new Error(`${this.id} rowOffsets length must equal output.length + 1`);if(e.columnIndices.length!==e.values.length)throw new Error(`${this.id} columnIndices and values must have equal length`);if(!Number.isSafeInteger(e.columns)||e.columns<0)throw new Error(`${this.id} columns must be a non-negative integer`);if(e.vector.length!==e.columns)throw new Error(`${this.id} vector length must equal columns`)}getStrategy(e){return ts(e.device,{rows:this.props.output.length,nonZeros:this.props.values.length,statistics:this.props.statistics},this.props.strategy)}explain(e){let t=this.getStrategy(e);return Object.freeze({operation:"GPUSpMV",strategy:t.id,score:t.score,reason:t.reason,...t.details})}getCommandNodes(e){let{rowOffsets:t,columnIndices:n,values:i,vector:o,output:s}=this.props;if(Qi(e,[t,n,i,o],[s]),!s.length)return[];let a=[],u=this.getStrategy(e),c=u.id,f=u.details.workgroupSize,d=c==="long-row"?u.details.workgroupsPerLongRow:1,l=ue(e,[go(e,t,0,s.length),go(e,t,1,s.length),s]),h=ue(e,[n,i]),m=Ae(Y(o)).filter(b=>b.length),p=e.device.limits.maxComputeWorkgroupsPerDimension,y=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(d*4)));if(y<1)throw new Error("SpMV count scratch must fit a storage binding");let g=[];for(let b of l)for(let P=0;P<b[0].length;P+=y){let B=Math.min(y,b[0].length-P);g.push(b.map(E=>e.createDataView(E.buffer,{format:E.format,length:B,byteOffset:E.byteOffset+P*4})))}let w=g.map(([b],P)=>c==="long-row"?H(e,`${this.id}-rows-${P}-partials`,"float32",b.length*d):void 0),S=m.length>1&&g.length*m.length>m.length+g.length,v=0,T=[];for(let[b,[P,B]]of h.entries()){let E;if(S){E=H(e,`${this.id}-gather-${b}`,"float32",P.length);let I=new Xr({id:`${this.id}-gather-${b}`,source:o,indices:P,output:E}).getCommandNodes(e);for(let[F,M]of I.entries())a.push(F===0?{...M,dependsOn:[...M.dependsOn??[],...T]}:M)}let G=E?[{data:E,offset:0}]:m,C=[];for(let[I,[F,M,ce]]of g.entries()){let ee=F.length,je=w[I];for(let[He,st]of G.entries()){let Bo=b===0&&He===0,Go=`${this.id}-rows-${I}-nonzeros-${b}-vector-${He}-${c}`,ws=c==="scalar-row"?Math.ceil(ee/f):ee*d,Do=$t(ws,p),Oo=je??ce;if(a.push(Hr(e,{id:Go,source:Pu({strategy:c,workgroupSize:f,parts:d,length:ee,begins:F,ends:M,indices:P,matrixValues:B,vector:st.data,output:Oo,nonzeroStart:v,vectorStart:st.offset,initialize:Bo,dispatch:Do,gathered:!!E,columns:this.props.columns}),inputs:{rowBegins:F,rowEnds:M,columnIndices:P,matrixValues:B,vectorValues:st.data},outputs:{[je?"rowPartials":"outputValues"]:Oo},dispatch:Do,workgroupSize:f})),je){let Uo=$t(Math.ceil(ee/64),p);a.push(Hr(e,{id:`${Go}-finalize`,inputs:{rowPartials:je},outputs:{outputValues:ce},dispatch:Uo,workgroupSize:64,source:`
316
+ }`}function cs(r){if(r.candidates.length===0)throw new Error("GPU strategy candidate list must not be empty");let e={device:r.device,workload:r.workload},t=r.candidates.filter(i=>i.isSupported?.(e)??!0);if(t.length===0)throw new Error("no supported GPU strategy candidate");if(r.preferredId){let i=t.find(s=>s.id===r.preferredId);if(!i)throw new Error(`preferred GPU strategy "${r.preferredId}" is not supported`);return us(i,e)}let n=t[0],o=n.score(e);for(let i=1;i<t.length;i++){let s=t[i],a=s.score(e);a>o&&(n=s,o=a)}return us(n,e,o)}function us(r,e,t=r.score(e)){return Object.freeze({id:r.id,score:t,reason:r.reason(e),details:Object.freeze(r.createDetails(e))})}function ds(r,e,t){if(!Number.isSafeInteger(e.rows)||e.rows<0)throw new Error("SpMV rows must be non-negative");if(!Number.isSafeInteger(e.nonZeros)||e.nonZeros<0)throw new Error("SpMV nonZeros must be non-negative");let n=e.nonZeros/Math.max(1,e.rows),o=e.statistics?.maxNonZerosPerRow,i=e.statistics?.shortRowFraction,s=kt(r,{requiresSubgroupId:!0})==="subgroups";return cs({device:r,workload:e,preferredId:t,candidates:[{id:"scalar-row",score:()=>n<=8?100:n<=16?60:10,reason:()=>`average row length ${n.toFixed(1)} favors one invocation per row`,createDetails:()=>({rowsPerWorkgroup:64,workgroupSize:64,workgroupsPerLongRow:1})},{id:"subgroup-row",isSupported:()=>s,score:()=>n<=64&&(i===void 0||i<.9)?110:35,reason:()=>"subgroups available; medium CSR rows can reduce within a subgroup",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:128,workgroupsPerLongRow:1})},{id:"workgroup-row",score:()=>n>32&&(o===void 0||o<=2048)?100:50,reason:()=>`average row length ${n.toFixed(1)} favors cooperative row reduction`,createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:1})},{id:"long-row",score:()=>o!==void 0&&o>2048||n>1024?140:0,reason:()=>"very long rows favor multi-workgroup partial reduction",createDetails:()=>({rowsPerWorkgroup:1,workgroupSize:256,workgroupsPerLongRow:4})}]})}var tn=class{id;props;constructor(e){this.id=e.id??"gpu-adaptive-spmv",this.props=e;for(let[t,n]of Object.entries({rowOffsets:e.rowOffsets,columnIndices:e.columnIndices,values:e.values,vector:e.vector,output:e.output})){for(let o of Y(n))pt(o,[t==="rowOffsets"||t==="columnIndices"?"uint32":"float32"],`${this.id} ${t}`);if(n.length>4294967295)throw new Error("SpMV logical lengths must fit in uint32")}if(e.rowOffsets.length!==e.output.length+1)throw new Error(`${this.id} rowOffsets length must equal output.length + 1`);if(e.columnIndices.length!==e.values.length)throw new Error(`${this.id} columnIndices and values must have equal length`);if(!Number.isSafeInteger(e.columns)||e.columns<0)throw new Error(`${this.id} columns must be a non-negative integer`);if(e.vector.length!==e.columns)throw new Error(`${this.id} vector length must equal columns`)}getStrategy(e){return ds(e.device,{rows:this.props.output.length,nonZeros:this.props.values.length,statistics:this.props.statistics},this.props.strategy)}explain(e){let t=this.getStrategy(e);return Object.freeze({operation:"GPUSpMV",strategy:t.id,score:t.score,reason:t.reason,...t.details})}getCommandNodes(e){let{rowOffsets:t,columnIndices:n,values:o,vector:i,output:s}=this.props;if(ss(e,[t,n,o,i],[s]),!s.length)return[];let a=[],u=this.getStrategy(e),c=u.id,d=u.details.workgroupSize,f=c==="long-row"?u.details.workgroupsPerLongRow:1,l=ce(e,[To(e,t,0,s.length),To(e,t,1,s.length),s]),h=ce(e,[n,o]),m=_e(Y(i)).filter(b=>b.length),g=e.device.limits.maxComputeWorkgroupsPerDimension,y=Math.min(4096,Math.floor(e.device.limits.maxStorageBufferBindingSize/(f*4)));if(y<1)throw new Error("SpMV count scratch must fit a storage binding");let p=[];for(let b of l)for(let P=0;P<b[0].length;P+=y){let B=Math.min(y,b[0].length-P);p.push(b.map(E=>e.createDataView(E.buffer,{format:E.format,length:B,byteOffset:E.byteOffset+P*4})))}let w=p.map(([b],P)=>c==="long-row"?q(e,`${this.id}-rows-${P}-partials`,"float32",b.length*f):void 0),S=m.length>1&&p.length*m.length>m.length+p.length,v=0,T=[];for(let[b,[P,B]]of h.entries()){let E;if(S){E=q(e,`${this.id}-gather-${b}`,"float32",P.length);let U=new en({id:`${this.id}-gather-${b}`,source:i,indices:P,output:E}).getCommandNodes(e);for(let[M,V]of U.entries())a.push(M===0?{...V,dependsOn:[...V.dependsOn??[],...T]}:V)}let O=E?[{data:E,offset:0}]:m,C=[];for(let[U,[M,V,de]]of p.entries()){let te=M.length,He=w[U];for(let[qe,ut]of O.entries()){let Uo=b===0&&qe===0,$o=`${this.id}-rows-${U}-nonzeros-${b}-vector-${qe}-${c}`,Os=c==="scalar-row"?Math.ceil(te/d):te*f,ko=_t(Os,g),Ao=He??de;if(a.push(Qr(e,{id:$o,source:_u({strategy:c,workgroupSize:d,parts:f,length:te,begins:M,ends:V,indices:P,matrixValues:B,vector:ut.data,output:Ao,nonzeroStart:v,vectorStart:ut.offset,initialize:Uo,dispatch:ko,gathered:!!E,columns:this.props.columns}),inputs:{rowBegins:M,rowEnds:V,columnIndices:P,matrixValues:B,vectorValues:ut.data},outputs:{[He?"rowPartials":"outputValues"]:Ao},dispatch:ko,workgroupSize:d})),He){let _o=_t(Math.ceil(te/64),g);a.push(Qr(e,{id:`${$o}-finalize`,inputs:{rowPartials:He},outputs:{outputValues:de},dispatch:_o,workgroupSize:64,source:`
317
317
  @group(0) @binding(0) var<storage, read> rowPartials: array<f32>;
318
318
  @group(0) @binding(1) var<storage, read_write> outputValues: array<f32>;
319
319
  @compute @workgroup_size(64)
320
320
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
321
- ${he(Uo,64)}
322
- if (index >= ${ee}u) { return; }
321
+ ${me(_o,64)}
322
+ if (index >= ${te}u) { return; }
323
323
  var sum = 0.0;
324
- for (var part = 0u; part < ${d}u; part++) {
325
- sum += rowPartials[index * ${d}u + part];
324
+ for (var part = 0u; part < ${f}u; part++) {
325
+ sum += rowPartials[index * ${f}u + part];
326
326
  }
327
- outputValues[${L(ce)}u + index] ${Bo?"=":"+="} sum;
328
- }`}))}}G.length&&C.push(a[a.length-1].id)}T=C,v+=P.length}if(!h.length||!m.length)for(let[b,[P,,B]]of g.entries()){let E=$t(Math.ceil(P.length/256),p);a.push(Hr(e,{id:`${this.id}-rows-${b}-clear`,outputs:{outputValues:B},dispatch:E,source:`
327
+ outputValues[${L(de)}u + index] ${Uo?"=":"+="} sum;
328
+ }`}))}}O.length&&C.push(a[a.length-1].id)}T=C,v+=P.length}if(!h.length||!m.length)for(let[b,[P,,B]]of p.entries()){let E=_t(Math.ceil(P.length/256),g);a.push(Qr(e,{id:`${this.id}-rows-${b}-clear`,outputs:{outputValues:B},dispatch:E,source:`
329
329
  @group(0) @binding(0) var<storage, read_write> outputValues: array<f32>;
330
330
  @compute @workgroup_size(256)
331
331
  fn main(@builtin(workgroup_id) workgroupId: vec3u, @builtin(local_invocation_index) localInvocationIndex: u32) {
332
- ${he(E,256)}
332
+ ${me(E,256)}
333
333
  if (index < ${P.length}u) {
334
334
  outputValues[${L(B)}u + index] = 0.0;
335
335
  }
336
- }`}))}return a}};function Pu(r){let{strategy:e,workgroupSize:t,parts:n,length:i,dispatch:o}=r,s=e==="subgroup-row",a=e==="workgroup-row"||e==="long-row",u=e==="long-row",c=u?"rowPartials":"outputValues";return`
336
+ }`}))}return a}};function _u(r){let{strategy:e,workgroupSize:t,parts:n,length:o,dispatch:i}=r,s=e==="subgroup-row",a=e==="workgroup-row"||e==="long-row",u=e==="long-row",c=u?"rowPartials":"outputValues";return`
337
337
  ${s?`enable subgroups;
338
338
  requires subgroup_id;`:""}
339
339
  @group(0) @binding(0) var<storage, read> rowBegins: array<u32>;
@@ -350,9 +350,9 @@ ${a?`var<workgroup> scratch: array<f32, ${t}>;`:""}
350
350
  @builtin(subgroup_invocation_id) subgroupLane: u32,
351
351
  @builtin(subgroup_size) subgroupSize: u32`:""}
352
352
  ) {
353
- let workgroupIndex = (workgroupId.z * ${o.y}u + workgroupId.y) * ${o.x}u + workgroupId.x;
353
+ let workgroupIndex = (workgroupId.z * ${i.y}u + workgroupId.y) * ${i.x}u + workgroupId.x;
354
354
  ${e==="scalar-row"?`let row = workgroupIndex * ${t}u + localInvocationIndex;`:`let row = workgroupIndex / ${n}u;`}
355
- if (row >= ${i}u) { return; }
355
+ if (row >= ${o}u) { return; }
356
356
  ${s?"if (subgroupId != 0u) { return; }":""}
357
357
  let begin = max(rowBegins[${L(r.begins)}u + row], ${r.nonzeroStart}u);
358
358
  let end = min(rowEnds[${L(r.ends)}u + row], ${r.nonzeroStart+r.indices.length}u);
@@ -386,9 +386,9 @@ ${a?`var<workgroup> scratch: array<f32, ${t}>;`:""}
386
386
  if (lane == 0u) {
387
387
  ${c}[${L(r.output)}u + row * ${n}u + ${u?"part":"0u"}] ${u||r.initialize?"=":"+="} sum;
388
388
  }
389
- }`}var Qr=class{props;id;constructor(e){if(this.props=e,this.id=e.id??"gpu-predicate-conjunction",e.inputs.length<2)throw new Error(`${this.id} requires at least two predicates`);let t=e.output.arena;if(e.inputs.some(n=>n.arena!==t))throw new Error(`${this.id} predicates must share one GPUValueArena`)}getCommandNodes(e){let{inputs:t,output:n}=this.props;if(n.arena.graph!==e)throw new Error(`${this.id} predicates must belong to target graph`);let i=n.arena.buffer,o=t.map(a=>`(${Se(a)} != 0u)`).join(" && "),s=`${me(0,0)}
390
- @compute @workgroup_size(1)fn main(){${ot(n,`select(0u,1u,${o})`)}}`;return[N({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:i,usage:"storage-write"}],compile:({device:a})=>{let u=new _(a,{id:this.id,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:f})=>{let d={gpuValues:f(i)};u.dispatch(c,{bindings:d,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};var q=class{id;type="composite";operations;metadata;constructor(e){let t=Array.isArray(e)?{operations:e}:e;this.id=t.id??"gpu-composite-operation",this.operations=Object.freeze([...t.operations]),this.metadata=t.metadata}};function Ee(r){let e=r;return typeof e.id=="string"&&typeof e.type=="string"}function yo(r){return r instanceof q?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{},children:Object.freeze(r.operations.map(yo))}):Ee(r)?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{}}):Object.freeze({id:r.constructor?.name??"gpu-command-node-producer",type:"command-node-producer"})}function rs(r){return typeof r.getCommandNodes=="function"}var At=class extends q{type="conditional";predicate;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];super({id:e.id??"gpu-conditional-operation",operations:t,metadata:e.metadata}),this.predicate=Object.freeze({...e.predicate}),this.lowering=e.lowering??"auto"}},it=class extends q{type="loop";predicate;maximumIterations;minimumIterations;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];if(super({id:e.id??"gpu-loop-operation",operations:t,metadata:e.metadata}),!Number.isSafeInteger(e.maximumIterations)||e.maximumIterations<1)throw new Error(`${this.id} maximumIterations must be a positive safe integer`);let n=e.minimumIterations??0;if(!Number.isSafeInteger(n)||n<0||n>e.maximumIterations)throw new Error(`${this.id} minimumIterations must be between zero and maximumIterations`);this.predicate=e.predicate?Object.freeze({...e.predicate}):void 0,this.maximumIterations=e.maximumIterations,this.minimumIterations=n,this.lowering=e.lowering??"auto"}};function _t(r){let e=r.clone(),t=new Map([...e.scalars,...e.vectors,...e.textures].map(o=>[o.id,o])),n=new Set,i=(o,s=!1)=>{if(o instanceof q){for(let a of o.operations)i(a,s||o.type!=="composite");return}if(Ee(o))try{let a=o.contract;if(!a)return;let u=typeof a.outputs=="function"?a.outputs({getValue(f){let d=t.get(f);if(!d)throw new Error(`Undeclared operation value ${f}`);return d instanceof ie?d.descriptor??W.texture({format:d.format,dimension:d.dimension,extent:{width:d.width,height:d.height,depth:d.depth},mipLevels:d.mipLevels,samples:d.samples}):d instanceof Oe?W.scalar(d.format):W.vector(d.format,{length:d.length,chunkLengths:d.chunkLengths})}}):a.outputs;for(let[f,d]of Object.entries(u??{})){if(!a.values.some(h=>h.access==="write"&&k(h.value)===f))throw new Error(`Operation result ${f} requires a write`);if(d.type==="texture"&&d.extent&&"like"in d.extent){let h=d.extent.like;if(!(t.get(h)instanceof ie)||!a.values.some(m=>m.access!=="write"&&k(m.value)===h))throw new Error(`Texture extent source ${h} must be a declared texture read`)}let l=t.get(f);if(l?.role==="input"||l?.role==="state")throw new Error(`Operation result conflicts with ${l.role} ${f}`);if(l){if(l.format!==d.format||l instanceof K!=(d.type==="vector")||l instanceof ie!=(d.type==="texture"))throw new Error(`Incompatible operation result ${f}`);l instanceof K&&d.type==="vector"&&t.set(f,e.constrainResult(l,d))}else{if(s)throw new Error("Operation results inside control flow require explicit declarations");let h=a.values.find(y=>k(y.value)===f&&y.access==="write")?.shape,m=d;if(d.type==="vector"&&d.length===void 0&&h){let y="like"in h?t.get(k(h.like)):void 0,g="length"in h?h:y instanceof K?y:void 0;g?.length!==void 0&&(m={...d,length:g.length,chunkLengths:d.chunkLengths??g.chunkLengths})}let p=e.addDeclaration(f,m,"value");t.set(f,p)}}Ot(e,a);for(let f of a.values){let d=k(f.value),l=t.get(d);if(f.access!=="read"&&l?.role==="input")throw new Error(`Cannot write graph input ${d}`);if(f.access!=="write"&&l?.role==="value"&&!n.has(d))throw new Error(`Reads ${d} before it is produced`)}let c=new Set(a.values.filter(f=>f.access!=="read").map(f=>k(f.value)));for(let f of c){if(t.get(f)?.role==="value"&&n.has(f))throw new Error(`Multiple writers for graph result ${f}`);n.add(f)}}catch(a){throw new Error(`${o.id}: ${a instanceof Error?a.message:String(a)}`,{cause:a})}};return e.operations.forEach(o=>i(o)),e}function ur(r,e={}){let t=[];try{r=_t(r)}catch(o){return{valid:!1,issues:[{level:"error",code:"invalid-operation-contract",message:o instanceof Error?o.message:String(o)}]}}for(let o of r.scalars)o.role==="input"&&e.scalars?.[o.id]===void 0&&t.push({level:"error",code:"missing-input",valueId:o.id,message:`Missing input binding ${o.id}`}),o.role==="value"&&e.scalars?.[o.id]!==void 0&&t.push({level:"error",code:"result-binding",valueId:o.id,message:`Cannot initialize graph result ${o.id}`});let n=new Set(r.scalars.map(o=>o.id));for(let o of r.vectors)o.external&&!e.vectors?.[o.id]&&t.push({level:"error",code:"missing-external-vector",valueId:o.id,message:`External vector "${o.id}" has no WebGPU binding`});let i=o=>{let s="id"in o&&typeof o.id=="string"?o.id:void 0;if(Ee(o))try{let a=o.contract;a&&Ot(r,a)}catch(a){t.push({level:"error",code:"invalid-operation-contract",operationId:s,message:`${s}: ${a instanceof Error?a.message:String(a)}`})}if(o instanceof At||o instanceof it){let a=o.predicate;a?.source==="gpu"&&(a.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" must use uint32 state`}),n.has(a.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" references undeclared scalar "${a.value.id}"`}))}if(o instanceof q)for(let a of o.operations)i(a)};for(let o of r.operations)i(o);return Object.freeze({valid:!t.some(o=>o.level==="error"),issues:Object.freeze(t.map(o=>Object.freeze({...o})))})}var xt=class{device;capabilities;lowerings;compactionIndex=0;constructor(e,t=[]){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1});let n=[...this.createCoreLowerings(),...t],i=new Set;for(let o of n){if(!o.type||i.has(o.type))throw new Error(`Duplicate or empty lowering type: ${o.type}`);i.add(o.type)}this.lowerings=Object.freeze(n.map(o=>Object.freeze({type:o.type,lower:o.lower.bind(o)})))}compile(e,t={}){this.compactionIndex=0,e=e.clone();for(let h of e.vectors){let m=t.vectors?.[h.id];if(!h.external||!m||h.chunkLengths)continue;let p="data"in m?m.data:"buffer"in m?[m]:m;e.constrainResult(h,{type:"vector",format:h.format,chunkLengths:p.map(y=>y.length)})}e=_t(e);let n=new Map,i=(h,m)=>{n.set(h,(n.get(h)??0)|m)},o=h=>{h instanceof q?h.operations.forEach(o):h instanceof Me?i(h.output,se.Buffer.COPY_DST):h instanceof Ve&&(i(h.input,se.Buffer.COPY_SRC),i(h.output,se.Buffer.COPY_DST))};e.operations.forEach(o);let s=ur(e,t);if(!s.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${s.issues.filter(h=>h.level==="error").map(h=>h.message).join("; ")}`);let a=new Rr(this.device,{id:`${e.id}-commands`}),u=new Map;for(let h of e.scalars)u.set(h.id,po(a,h.id,h.format));for(let[h,m]of Object.entries(t.scalars??{})){let p=u.get(h);if(!p)throw new Error(`Undeclared scalar binding ${h}`);let y=p.view;a.addCopyPass({id:`${h}-binding`,resources:[{buffer:y,usage:"copy-destination"}],compile:({device:g})=>{let w=p.format==="float32"?new Float32Array([m]):p.format==="uint32"?new Uint32Array([m]):new Int32Array([m]),S=g.createBuffer({data:w,usage:se.Buffer.COPY_SRC});return{encode:({commandEncoder:v,getBuffer:T})=>v.copyBufferToBuffer({sourceBuffer:S,destinationBuffer:T(y),destinationOffset:y.byteOffset,size:4}),destroy:()=>S.destroy()}}})}let c=new Map;for(let h of e.vectors){if(h.length===void 0)throw new Error(`${h.id}: bind dynamic dimensions through program.compile(device).run(bindings)`);let m;if(h.external){let p=t.vectors[h.id],y="data"in p?p:{format:h.format,length:h.length,data:"buffer"in p?[p]:p};if(m=a.importGPUVector(h.id,y),m.format!==h.format||m.length!==h.length)throw new Error(`${h.id} binding format and length must match its logical vector`);if(h.chunkLengths&&(h.chunkLengths.length!==m.data.length||h.chunkLengths.some((g,w)=>g!==m.data[w].length)))throw new Error(`${h.id} binding must preserve its declared chunk topology`)}else{let p=h.chunkLengths??Cu(h.length,this.device,U(h.format).byteLength),y=p.map((w,S)=>H(a,p.length===1?h.id:`${h.id}-chunk-${S}`,h.format,w,h.role==="value"?se.Buffer.STORAGE|se.Buffer.VERTEX|se.Buffer.COPY_SRC|se.Buffer.COPY_DST:se.Buffer.STORAGE|(n.get(h.id)??0))),g=U(h.format);m=new D({id:h.id,name:h.id,format:h.format,length:h.length,valueLength:h.length,stride:g.components,byteStride:g.byteLength,rowByteLength:g.byteLength,data:y})}c.set(h.id,m)}let f=new Map,d=new Map;for(let h of e.textures){(0,se.assert)(h.width!==void 0&&h.height!==void 0);let m=t.textures?.[h.id],p={...h,width:h.width,height:h.height};if(m instanceof se.TextureView){let g=ae(m);(0,se.assert)(g.format===h.format&&g.width===h.width&&g.height===h.height),d.set(h.id,m),m=g.texture,p={...p,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples}}let y=h.external?a.importTexture(p,m):a.createTransientTexture(p);f.set(h.id,y)}let l={path:[],nodes:[],decisions:[],predicates:[],scalars:u,vectors:c,textures:f,textureValues:e.textures,textureViews:d,predicateConjunctions:new Map,commandNodeIds:new Set,transientResultNames:new Set(e.vectors.filter(h=>h.role==="value"&&!h.external).map(h=>h.id)),retainedBuffers:[]};for(let h of e.operations)this.lower(a,h,l);return Object.freeze({program:e,graph:a,scalars:u,vectors:c,textures:f,validation:s,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(l.nodes.map(h=>Object.freeze({...h,operationPath:Object.freeze([...h.operationPath])}))),decisions:Object.freeze(l.decisions.map(h=>Object.freeze({...h})))})})}createCoreLowerings(){return[{type:"vector-upload",lower:_i},{type:"vector-copy",lower:Fi},{type:"compaction",lower:(e,t)=>{let{input:n,flags:i,output:o,count:s}=e.props;t.graph.add(new Fr({id:`${e.id}-${this.compactionIndex++}`,input:t.resolveVector(n),flags:t.resolveVector(i),output:t.resolveVector(o),count:t.resolveScalar(s).view}))}},{type:"scalar-literal",lower:(e,t)=>{let n=new It({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-literal",reason:"host-known literal lowers to one compute command node"})}},{type:"scalar-operation",lower:(e,t)=>{let n=new zr({id:e.id,operation:e.operation,left:t.resolveScalar(e.left),right:e.right?t.resolveScalar(e.right):void 0,output:t.resolveScalar(e.output)});this.emitProducer(t.graph,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}},{type:"vector-madd",lower:(e,t)=>{let n=e.props,i=new jr({id:e.id,input:t.resolveVector(n.input),scale:t.resolveScalar(n.scale),addend:t.resolveVector(n.addend),output:t.resolveVector(n.output)});this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}},{type:"dot-product",lower:(e,t)=>{let n=e.props,i=new qr({id:e.id,left:t.resolveVector(n.left),right:t.resolveVector(n.right),output:t.resolveScalar(n.output)});this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}},{type:"spmv",lower:(e,t)=>{let n=e.props,i=n.matrix,o=new Kr({id:e.id,rowOffsets:t.resolveVector(i.rowOffsets),columnIndices:t.resolveVector(i.columnIndices),values:t.resolveVector(i.values),vector:t.resolveVector(n.vector),output:t.resolveVector(n.output),columns:i.columns,statistics:i.statistics,strategy:n.strategy}),s=o.getStrategy(t.graph);this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${s.id}`,reason:s.reason})}},{type:"conditional",lower:(e,t)=>{t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-indirect-gate",reason:"WebGPU realizes runtime predicates with zero/nonzero indirect dispatch"});for(let n of e.operations)t.lowerConditional(e.predicate,n)}},{type:"loop",lower:(e,t)=>{if(!e.predicate||e.lowering==="unroll"){t.recordDecision({operationId:e.id,operationType:e.type,lowering:"bounded-unroll",reason:e.predicate?"explicit unroll preference":"loop has no runtime predicate"});for(let n=0;n<e.maximumIterations;n++)for(let i of e.operations)t.lower(i);return}t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-gated-bounded-sequence",reason:"WebGPU has indirect dispatch but no native graph loop"});for(let n=0;n<e.maximumIterations;n++){let i=n>=e.minimumIterations;for(let o of e.operations)i?t.lowerConditional(e.predicate,o):t.lower(o)}}}]}lower(e,t,n){let i="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";n.path.push(i);let o=n.retainedBuffers,s=[...o];if(Ee(t))for(let a of t.contract?.values??[]){let u=typeof a.value=="string"?a.value:a.value.id;if(n.transientResultNames.has(u))for(let c of n.vectors.get(u).data)s.push(c.buffer)}n.retainedBuffers=s;try{if(t instanceof q&&t.type==="composite"){n.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let a of t.operations)this.lower(e,a,n);return}if(Ee(t)){for(let u of t.contract?.requiredFeatures??[])if(!this.device.features.has(u))throw new Error(`${i} requires ${u}`);let a=this.lowerings.find(u=>u.type===t.type)?.lower;if(a){let u=()=>(t instanceof Ve&&n.textureValues.some(c=>c.id===t.input)?Ri:a)(t,{graph:e,capabilities:this.capabilities,lower:c=>this.lower(e,c,n),lowerConditional:(c,f)=>{n.predicates.push(c);try{this.lower(e,f,n)}finally{n.predicates.pop()}},resolveScalar:c=>this.resolveScalar(c,n),resolveVector:c=>this.resolveVector(c,n),resolveTexture:c=>this.resolveTexture(c,n),resolveTextureView:c=>{let f=c instanceof Ue?c.texture:c,d=c instanceof Ue?c.props:{},l=n.textureViews.get(typeof f=="string"?f:f.id);return e.createTextureView(this.resolveTexture(f,n),l?$i(l,d):d)},recordDecision:c=>n.decisions.push(c)});t instanceof At||t instanceof it?u():this.withNodeDecoration(e,n,u);return}}if("getNodes"in t||rs(t)){n.decisions.push({operationId:i,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,n,()=>e.add(t));return}throw new Error(`GPUGraph operation "${i}" has no WebGPU lowering`)}finally{n.retainedBuffers=o,n.path.pop()}}emitProducer(e,t,n){let i=t.getCommandNodes(e);if(!n){Re(e,i);return}if(i.length!==n.length)throw new Error(`lowering produced ${i.length} command nodes but declared ${n.length} dispatches`);let o=i.map((s,a)=>this.attachDispatch(s,n[a]));Re(e,o)}attachDispatch(e,t){if(e.type!=="compute")throw new Error(`dispatch geometry can only be attached to compute command nodes; got ${e.type} node "${e.id}"`);return z(e,t)}withNodeDecoration(e,t,n){return e.withComputeLowering(i=>this.decorateComputeNode(e,i,t),()=>e.withOtherLowering(i=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${i.type} node "${i.id}"`);let o=this.makeCommandNodeIdUnique(i,t);return t.nodes.push({nodeId:o.id,nodeType:o.type,operationPath:[...t.path]}),{...o,retainedBuffers:t.retainedBuffers}},n))}decorateComputeNode(e,t,n){if(t={...this.makeCommandNodeIdUnique(t,n),retainedBuffers:n.retainedBuffers},n.path.length&&n.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...n.path]}),!n.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let i=Ar(t);if(!i)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let o;if(n.predicates.length===1)o=n.scalars.get(n.predicates[0].value.id);else{let u=n.predicates.map(l=>l.value.id).join("&&"),c=n.predicateConjunctions.get(u);c||(c=po(e,`predicate-and-${n.predicateConjunctions.size}`,"uint32"),n.predicateConjunctions.set(u,c));let f=n.predicates.map(l=>n.scalars.get(l.value.id)),d=new Qr({id:`${t.id}-predicate-and`,inputs:f,output:c}).getCommandNodes(e).map(l=>this.attachDispatch(l,[1,1,1]));e.withoutComputeLowering(()=>Re(e,d)),o=c}if(!o)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let s=new ar(e,{id:`${t.id}-predicate`,active:o,workgroups:i}),a=s.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>Re(e,a)),{...t,condition:s.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let n=1,i=`${e.id}-iteration-${n}`;for(;t.commandNodeIds.has(i);)n++,i=`${e.id}-iteration-${n}`;return t.commandNodeIds.add(i),{...e,id:i}}resolveTexture(e,t){let n=typeof e=="string"?e:e.id;if(typeof e=="string"?!t.textures.has(n):!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${n}"`);return t.textures.get(n)}resolveScalar(e,t){let n=typeof e=="string"?e:e.id,i=t.scalars.get(n);if(!i||typeof e!="string"&&i.format!==e.format)throw new Error(`GPUGraph scalar "${n}" is not part of compilation`);return i}resolveVector(e,t){let n=typeof e=="string"?e:e.id,i=t.vectors.get(n);if(!i||typeof e!="string"&&(i.format!==e.format||e.length!==void 0&&i.length!==e.length))throw new Error(`GPUGraph vector "${n}" is not part of compilation`);return i}};function Cu(r,e,t){let n=Math.floor(e.limits.maxStorageBufferBindingSize/t);if(n<1||r<=n)return[r];let i=[];for(let o=0;o<r;o+=n)i.push(Math.min(n,r-o));return i}var ge=V(R(),1);var Lu=class{add(r,e,t){if(typeof arguments[0]!="string")for(let n in arguments[0])this.add(n,arguments[0][n],arguments[1]);else(Array.isArray(r)?r:[r]).forEach(function(n){this[n]=this[n]||[],e&&this[n][t?"unshift":"push"](e)},this)}run(r,e){this[r]=this[r]||[],this[r].forEach(function(t){t.call(e&&e.context?e.context:e,e)})}},Bu=class{constructor(r){this.jsep=r,this.registered={}}register(...r){r.forEach(e=>{if(typeof e!="object"||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)})}},pe=class x{static get version(){return"1.4.0"}static toString(){return"JavaScript Expression Parser (JSEP) v"+x.version}static addUnaryOp(e){return x.max_unop_len=Math.max(e.length,x.max_unop_len),x.unary_ops[e]=1,x}static addBinaryOp(e,t,n){return x.max_binop_len=Math.max(e.length,x.max_binop_len),x.binary_ops[e]=t,n?x.right_associative.add(e):x.right_associative.delete(e),x}static addIdentifierChar(e){return x.additional_identifier_chars.add(e),x}static addLiteral(e,t){return x.literals[e]=t,x}static removeUnaryOp(e){return delete x.unary_ops[e],e.length===x.max_unop_len&&(x.max_unop_len=x.getMaxKeyLen(x.unary_ops)),x}static removeAllUnaryOps(){return x.unary_ops={},x.max_unop_len=0,x}static removeIdentifierChar(e){return x.additional_identifier_chars.delete(e),x}static removeBinaryOp(e){return delete x.binary_ops[e],e.length===x.max_binop_len&&(x.max_binop_len=x.getMaxKeyLen(x.binary_ops)),x.right_associative.delete(e),x}static removeAllBinaryOps(){return x.binary_ops={},x.max_binop_len=0,x}static removeLiteral(e){return delete x.literals[e],x}static removeAllLiterals(){return x.literals={},x}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new x(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map(t=>t.length))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return x.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!x.binary_ops[String.fromCharCode(e)]||x.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return x.isIdentifierStart(e)||x.isDecimalDigit(e)}throwError(e){let t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(x.hooks[e]){let n={context:this,node:t};return x.hooks.run(e,n),n.node}return t}searchHook(e){if(x.hooks[e]){let t={context:this};return x.hooks[e].find(function(n){return n.call(t.context,t),t.node}),t.node}}gobbleSpaces(){let e=this.code;for(;e===x.SPACE_CODE||e===x.TAB_CODE||e===x.LF_CODE||e===x.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");let e=this.gobbleExpressions(),t=e.length===1?e[0]:{type:x.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t=[],n,i;for(;this.index<this.expr.length;)if(n=this.code,n===x.SEMCOL_CODE||n===x.COMMA_CODE)this.index++;else if(i=this.gobbleExpression())t.push(i);else if(this.index<this.expr.length){if(n===e)break;this.throwError('Unexpected "'+this.char+'"')}return t}gobbleExpression(){let e=this.searchHook("gobble-expression")||this.gobbleBinaryExpression();return this.gobbleSpaces(),this.runHook("after-expression",e)}gobbleBinaryOp(){this.gobbleSpaces();let e=this.expr.substr(this.index,x.max_binop_len),t=e.length;for(;t>0;){if(x.binary_ops.hasOwnProperty(e)&&(!x.isIdentifierStart(this.code)||this.index+e.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+e.length))))return this.index+=t,e;e=e.substr(0,--t)}return!1}gobbleBinaryExpression(){let e,t,n,i,o,s,a,u,c;if(s=this.gobbleToken(),!s||(t=this.gobbleBinaryOp(),!t))return s;for(o={value:t,prec:x.binaryPrecedence(t),right_a:x.right_associative.has(t)},a=this.gobbleToken(),a||this.throwError("Expected expression after "+t),i=[s,o,a];t=this.gobbleBinaryOp();){if(n=x.binaryPrecedence(t),n===0){this.index-=t.length;break}o={value:t,prec:n,right_a:x.right_associative.has(t)},c=t;let f=d=>o.right_a&&d.right_a?n>d.prec:n<=d.prec;for(;i.length>2&&f(i[i.length-2]);)a=i.pop(),t=i.pop().value,s=i.pop(),e={type:x.BINARY_EXP,operator:t,left:s,right:a},i.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+c),i.push(o,e)}for(u=i.length-1,e=i[u];u>1;)e={type:x.BINARY_EXP,operator:i[u-1].value,left:i[u-2],right:e},u-=2;return e}gobbleToken(){let e,t,n,i;if(this.gobbleSpaces(),i=this.searchHook("gobble-token"),i)return this.runHook("after-token",i);if(e=this.code,x.isDecimalDigit(e)||e===x.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===x.SQUOTE_CODE||e===x.DQUOTE_CODE)i=this.gobbleStringLiteral();else if(e===x.OBRACK_CODE)i=this.gobbleArray();else{for(t=this.expr.substr(this.index,x.max_unop_len),n=t.length;n>0;){if(x.unary_ops.hasOwnProperty(t)&&(!x.isIdentifierStart(this.code)||this.index+t.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+t.length)))){this.index+=n;let o=this.gobbleToken();return o||this.throwError("missing unaryOp argument"),this.runHook("after-token",{type:x.UNARY_EXP,operator:t,argument:o,prefix:!0})}t=t.substr(0,--n)}x.isIdentifierStart(e)?(i=this.gobbleIdentifier(),x.literals.hasOwnProperty(i.name)?i={type:x.LITERAL,value:x.literals[i.name],raw:i.name}:i.name===x.this_str&&(i={type:x.THIS_EXP})):e===x.OPAREN_CODE&&(i=this.gobbleGroup())}return i?(i=this.gobbleTokenProperty(i),this.runHook("after-token",i)):this.runHook("after-token",!1)}gobbleTokenProperty(e){this.gobbleSpaces();let t=this.code;for(;t===x.PERIOD_CODE||t===x.OBRACK_CODE||t===x.OPAREN_CODE||t===x.QUMARK_CODE;){let n;if(t===x.QUMARK_CODE){if(this.expr.charCodeAt(this.index+1)!==x.PERIOD_CODE)break;n=!0,this.index+=2,this.gobbleSpaces(),t=this.code}this.index++,t===x.OBRACK_CODE?(e={type:x.MEMBER_EXP,computed:!0,object:e,property:this.gobbleExpression()},e.property||this.throwError('Unexpected "'+this.char+'"'),this.gobbleSpaces(),t=this.code,t!==x.CBRACK_CODE&&this.throwError("Unclosed ["),this.index++):t===x.OPAREN_CODE?e={type:x.CALL_EXP,arguments:this.gobbleArguments(x.CPAREN_CODE),callee:e}:(t===x.PERIOD_CODE||n)&&(n&&this.index--,this.gobbleSpaces(),e={type:x.MEMBER_EXP,computed:!1,object:e,property:this.gobbleIdentifier()}),n&&(e.optional=!0),this.gobbleSpaces(),t=this.code}return e}gobbleNumericLiteral(){let e="",t,n;for(;x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(this.code===x.PERIOD_CODE)for(e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(t=this.char,t==="e"||t==="E"){for(e+=this.expr.charAt(this.index++),t=this.char,(t==="+"||t==="-")&&(e+=this.expr.charAt(this.index++));x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.expr.charCodeAt(this.index-1))||this.throwError("Expected exponent ("+e+this.char+")")}return n=this.code,x.isIdentifierStart(n)?this.throwError("Variable names cannot start with a number ("+e+this.char+")"):(n===x.PERIOD_CODE||e.length===1&&e.charCodeAt(0)===x.PERIOD_CODE)&&this.throwError("Unexpected period"),{type:x.LITERAL,value:parseFloat(e),raw:e}}gobbleStringLiteral(){let e="",t=this.index,n=this.expr.charAt(this.index++),i=!1;for(;this.index<this.expr.length;){let o=this.expr.charAt(this.index++);if(o===n){i=!0;break}else if(o==="\\")switch(o=this.expr.charAt(this.index++),o){case"n":e+=`
391
- `;break;case"r":e+="\r";break;case"t":e+=" ";break;case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:e+=o}else e+=o}return i||this.throwError('Unclosed quote after "'+e+'"'),{type:x.LITERAL,value:e,raw:this.expr.substring(t,this.index)}}gobbleIdentifier(){let e=this.code,t=this.index;for(x.isIdentifierStart(e)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(e=this.code,x.isIdentifierPart(e));)this.index++;return{type:x.IDENTIFIER,name:this.expr.slice(t,this.index)}}gobbleArguments(e){let t=[],n=!1,i=0;for(;this.index<this.expr.length;){this.gobbleSpaces();let o=this.code;if(o===e){n=!0,this.index++,e===x.CPAREN_CODE&&i&&i>=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}else if(o===x.COMMA_CODE){if(this.index++,i++,i!==t.length){if(e===x.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===x.CBRACK_CODE)for(let s=t.length;s<i;s++)t.push(null)}}else if(t.length!==i&&i!==0)this.throwError("Expected comma");else{let s=this.gobbleExpression();(!s||s.type===x.COMPOUND)&&this.throwError("Expected comma"),t.push(s)}}return n||this.throwError("Expected "+String.fromCharCode(e)),t}gobbleGroup(){this.index++;let e=this.gobbleExpressions(x.CPAREN_CODE);if(this.code===x.CPAREN_CODE)return this.index++,e.length===1?e[0]:e.length?{type:x.SEQUENCE_EXP,expressions:e}:!1;this.throwError("Unclosed (")}gobbleArray(){return this.index++,{type:x.ARRAY_EXP,elements:this.gobbleArguments(x.CBRACK_CODE)}}},Gu=new Lu;Object.assign(pe,{hooks:Gu,plugins:new Bu(pe),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"??":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10,"**":11},right_associative:new Set(["**"]),additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"});pe.max_unop_len=pe.getMaxKeyLen(pe.unary_ops);pe.max_binop_len=pe.getMaxKeyLen(pe.binary_ops);var cr=r=>new pe(r).parse(),Du=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(pe).filter(r=>!Du.includes(r)&&cr[r]===void 0).forEach(r=>{cr[r]=pe[r]});cr.Jsep=pe;var Ou="ConditionalExpression",Uu={name:"ternary",init(r){r.hooks.add("after-expression",function(t){if(t.node&&this.code===r.QUMARK_CODE){this.index++;let n=t.node,i=this.gobbleExpression();if(i||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===r.COLON_CODE){this.index++;let o=this.gobbleExpression();if(o||this.throwError("Expected expression"),t.node={type:Ou,test:n,consequent:i,alternate:o},n.operator&&r.binary_ops[n.operator]<=.9){let s=n;for(;s.right.operator&&r.binary_ops[s.right.operator]<=.9;)s=s.right;t.node.test=s.right,s.right=t.node,t.node=n}}else this.throwError("Expected :")}})}};cr.plugins.register(Uu);var ns=cr;var Iu=ns;function bo(r){return typeof r=="string"?Iu(r):r}var Ie=class{get contract(){let e=Zr(this.expression),t=Jr(e);return{outputs:({getValue:n})=>{let i=t.map(a=>{let u=n(a);if(u.type==="texture")throw new Error("Numeric expressions cannot read textures");return[a,u]}),o=de(e,new Map(i.map(([a,u])=>[a,u.format]))),s=i.some(([,a])=>a.type==="vector");return{[this.output]:s||!os(o)?W.vector(o,s?{}:{length:1}):W.scalar(o)}},values:[...Jr(Zr(this.expression)).map(n=>({value:n,access:"read"})),{value:this.output,access:"write"}]}}type="expression";id;output;expression;integerRounding;constructor(e){this.id=e.id??`${e.output}-expression`,this.output=e.output,this.expression=e.expression,this.integerRounding=e.integerRounding??"truncate"}};function xo(r){return/^(float32|sint32|uint32)(x[234])?$/.test(r)}function Z(r){let e=U(r);return{components:e.components,componentType:e.signedDataType}}function dr(r,e){return e===1?r:`${r}x${e}`}function Zr(r){let e=t=>{let n=t;switch(n.type){case"Identifier":return{kind:"reference",name:n.name};case"Literal":if(typeof n.value=="number"&&Number.isFinite(Math.fround(n.value)))return{kind:"literal",value:n.value};break;case"UnaryExpression":if(n.operator==="-")return{kind:"negate",argument:e(n.argument)};break;case"MemberExpression":{let i=n.property;if(n.computed||i.type!=="Identifier")throw new Error("Computed component access is unsupported");if(!/^[xyzw]{1,4}$/.test(i.name))throw new Error(`Invalid swizzle .${i.name}: expected 1\u20134 xyzw components`);return{kind:"swizzle",argument:e(n.object),components:[...i.name].map(o=>"xyzw".indexOf(o))}}case"CallExpression":{let i=n.callee;if(i.type!=="Identifier")break;let o=i.name;if(/^vec[234]$/.test(o)){if(n.arguments.length<1||n.arguments.length>4)throw new Error(`${o}: expected 1\u20134 arguments, received ${n.arguments.length}`);return{kind:"construct",width:Number(o[3]),arguments:n.arguments.map(e)}}if(os(o)){if(n.arguments.length!==1)throw new Error(`Invalid argument count for ${o}`);return{kind:"cast",format:o,argument:e(n.arguments[0])}}if(!["abs","sqrt","pow","sin","cos","tan","exp","log","dot","length","equalAll","select"].includes(o))break;let s=o==="select"?3:["pow","dot","equalAll"].includes(o)?2:1;if(n.arguments.length!==s)throw new Error(`Invalid argument count for GPU expression function ${o}`);return{kind:"call",name:o,arguments:n.arguments.map(e)}}case"BinaryExpression":if(["+","-","*","/"].includes(n.operator))return{kind:"binary",operator:n.operator,left:e(n.left),right:e(n.right)};break}throw new Error(`Unsupported GPU expression syntax: ${n.type}`)};return e(typeof r=="string"?bo(r):r)}function Jr(r){let e=new Set,t=n=>{switch(n.kind){case"reference":e.add(n.name);break;case"swizzle":case"cast":case"negate":t(n.argument);break;case"construct":case"call":n.arguments.forEach(t);break;case"binary":t(n.left),t(n.right);break}};return t(r),[...e]}function os(r){return r==="float32"||r==="sint32"||r==="uint32"}function de(r,e){switch(r.kind){case"literal":return"float32";case"reference":{let t=e.get(r.name);if(!t)throw new Error(`Undeclared numeric input ${r.name}`);return t}case"swizzle":{let t=Z(de(r.argument,e)),n=Math.max(...r.components)+1;if(n>t.components){let i=r.components.map(s=>"xyzw"[s]).join(""),o=r.argument.kind==="reference"?r.argument.name:"input";throw new Error(`.${i} needs ${n} components; ${o} has ${t.components}`)}return dr(t.componentType,r.components.length)}case"construct":{let t=r.arguments.map(o=>Z(de(o,e))),n=t[0].componentType;if(t.some(o=>o.componentType!==n))throw new Error(`vec${r.width}: mixed component types (${t.map(o=>o.componentType).join(", ")})`);let i=t.reduce((o,s)=>o+s.components,0);if(!(t.length===1&&i===1)&&i!==r.width)throw new Error(`vec${r.width}(...) needs ${r.width} components; received ${i}`);return dr(n,r.width)}case"cast":return dr(r.format,Z(de(r.argument,e)).components);default:{let n=(r.kind==="call"?r.arguments:r.kind==="negate"?[r.argument]:[r.left,r.right]).map(o=>Z(de(o,e)));if(r.kind==="call"){let[o,s,a]=n;if(r.name==="equalAll"){if(o.componentType!==s.componentType||o.components!==s.components)throw new Error("equalAll requires matching types and row widths");return"uint32"}if(r.name==="select"){if(s.componentType!==a.componentType)throw new Error("select branches require matching component types");let u=Math.max(s.components,a.components);if(n.some(c=>c.components!==1&&c.components!==u))throw new Error("select widths must match its branches or be one component");return dr(s.componentType,u)}if(r.name==="dot"&&o.components!==s.components)throw new Error("dot requires matching row widths")}if(n.some(o=>o.componentType!=="float32"))throw new Error("Arithmetic requires float32 operands; use an explicit float32 cast");if(r.kind==="call"&&(r.name==="dot"||r.name==="length"))return"float32";let i=Math.max(...n.map(o=>o.components));if(n.some(o=>o.components!==1&&o.components!==i))throw new Error("Expression row widths must match or broadcast from one component");return dr("float32",i)}}}var Ft=class{contracts=new Map;resultNames;expressions;operations;outputs;scalars;vectors;textures;constructor(e,t={}){e=_t(e),this.scalars=e.scalars,this.vectors=e.vectors,this.textures=e.textures;let n=[],i=m=>{if(m instanceof q&&m.type==="composite")m.operations.forEach(i);else{if(m instanceof q){let p=y=>y instanceof Ie||y instanceof q&&y.operations.some(p);if(m.operations.some(p))throw new Error("Expression operations inside control flow are not supported")}n.push(m)}};e.operations.forEach(i),this.operations=n;let o=new Map([...this.scalars,...this.vectors,...this.textures].map(m=>[m.id,m])),s=n.filter(m=>m instanceof Ie),a=new Set,u=new Map;for(let m of n)if(m instanceof Ie&&u.set(m,new Set(a)),!!Ee(m))try{let p=ss(m,this.scalars);if(!p)continue;Ot(e,p),this.contracts.set(m,p);for(let y of p.values){let g=k(y.value);y.access!=="read"&&this.scalars.some(w=>w.id===g)&&a.add(g)}}catch(p){throw new Error(`${m.id}: ${p instanceof Error?p.message:String(p)}`,{cause:p})}let c=new Set;for(let m of s){if(c.has(m.output))throw new Error(`Multiple expression writers for ${m.output}`);c.add(m.output)}let f=new Set([...o.keys()].filter(m=>!c.has(m)&&o.get(m)?.role!=="value")),d=[];for(let m of n){let p=this.contracts.get(m);if(!(m instanceof Ie)){for(let y of p?.values??[]){let g=k(y.value);if(y.access!=="write"&&!f.has(g))throw new Error(`${"id"in m?m.id:"Operation"}: Reads ${g} before it is produced`)}for(let y of p?.values??[])y.access!=="read"&&f.add(k(y.value));continue}try{let y=o.get(m.output);if(!y||!xo(y.format))throw new Error(`Expression output ${m.output} must declare a 32-bit numeric row of width 1\u20134`);let g=Zr(m.expression),w=Jr(g);if(w.includes(m.output))throw new Error(`Reads ${m.output} before it is produced`);let S=new Map;for(let b of w){let P=o.get(b);if(!P||!xo(P.format))throw new Error(`Expression input ${b} must declare a 32-bit numeric row of width 1\u20134`);if(S.set(b,P.format),!f.has(b))throw new Error(`Reads ${b} before it is produced`)}if(this.scalars.some(b=>b.id===y.id)&&w.some(b=>this.vectors.some(P=>P.id===b)))throw new Error(`Vector expression cannot write scalar ${m.output}`);if(this.vectors.some(b=>b.id===m.output)&&!w.some(b=>this.vectors.some(P=>P.id===b))&&!(y instanceof K&&y.role==="value"&&y.length!==void 0))throw new Error(`Vector expression ${m.output} requires a vector input to determine its shape`);let v=de(g,S);if(y.format!==v)throw new Error("Expression result type must match its output declaration");f.add(m.output);let T=w.filter(b=>u.get(m).has(b));d.push({operation:m,expression:g,format:v,formats:S,references:w,gpuScalarInputs:T})}catch(y){throw y instanceof Error?new Error(`${m.id}: ${y.message}`,{cause:y}):y}}this.expressions=d;let l=[...o.values()].filter(m=>m.role==="value");this.resultNames=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(p=>p.access!=="read").map(p=>k(p.value))).filter(m=>o.get(m)?.role!=="input"&&o.get(m)?.role!=="state"));let h=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(p=>p.access!=="write").map(p=>k(p.value))));this.outputs=[...t.outputs??(l.length?[...this.resultNames].filter(m=>!h.has(m)):s.map(m=>m.output))];for(let m of this.outputs){if(!o.has(m))throw new Error(`Undeclared output ${m}`);if(this.scalars.some(p=>p.id===m)&&!c.has(m)&&!a.has(m))throw new Error(`Selected scalar ${m} must be produced by a graph operation`)}}resolveBindings(e,t={}){let n=[...this.scalars,...this.vectors,...this.textures];if(!(n.some(c=>c.role==="input"||c.role==="state")||Object.values(e).some(c=>c!==void 0&&typeof c=="object"&&!(c instanceof j)&&!(c instanceof we)&&!(c instanceof ge.Texture)&&!(c instanceof ge.TextureView)))){for(let c of Object.keys(e))if(n.find(f=>f.id===c)?.role==="value")throw new Error(`Use outputTargets for graph result ${c}`);return{bindings:e,options:t}}for(let c of Object.keys(e))if(!["inputs","state","outputTargets"].includes(c))throw new Error(`Unknown execution option ${c}`);let s=e,a=Object.create(null);for(let[c,f]of[["input",s.inputs],["state",s.state]])for(let[d,l]of Object.entries(f??{})){let h=n.find(p=>p.id===d),m=h?.role??(this.resultNames.has(d)?"value":"input");if(!h||m!==c)throw new Error(`Invalid ${c} binding ${d}`);a[d]=l}for(let c of n)if((c.role==="input"||c.role==="state")&&a[c.id]===void 0)throw new Error(`Missing ${c.role} binding ${c.id}`);if(t.outputTargets&&s.outputTargets)throw new Error("Duplicate output targets");let u=s.outputTargets??t.outputTargets;for(let c of Object.keys(u??{}))if(!this.resultNames.has(c)||!this.outputs.includes(c))throw new Error(`Invalid graph output target ${c}`);return{bindings:a,options:{outputTargets:u}}}prepare(e,t,n={},i=!1){let o=new kr(e,this.textures,[...this.contracts.values()],t,n.outputTargets??{}),s=new Map,a=new Set,u=new Map,c=i&&!this.operations.some(g=>g instanceof q),f=g=>{let w=s.get(g);return w instanceof j?{length:w.length,chunkLengths:w.data.map(S=>S.length)}:u.get(g)},d=(g,w,S)=>{if(c&&!this.outputs.includes(g)&&this.vectors.some(v=>v.id===g&&v.role==="value"))u.set(g,{length:w.reduce((v,T)=>v+T,0),chunkLengths:w});else{let v=is(e,g,w,S);a.add(v),s.set(g,v)}},l=new Set(this.expressions.map(g=>g.operation.output)),h=new Map;for(let[g,w]of Object.entries(n.outputTargets??{}))if(!this.textures.some(S=>S.id===g)){if(!(w instanceof j))throw o.destroy(),new Error(`Expected GPUVector ${g}`);h.set(g,w)}let m=new Set([...this.contracts.values()].flatMap(g=>g.values.filter(w=>w.access!=="read"&&this.vectors.some(S=>S.id===k(w.value))).map(w=>k(w.value)))),p=new Set,y=new Set;try{for(let[g,w]of Object.entries(t)){if(this.textures.some(T=>T.id===g))continue;if(l.has(g))throw new Error(`Use outputTargets for expression output ${g}`);let S=this.scalars.find(T=>T.id===g),v=this.vectors.find(T=>T.id===g);if(S){if(typeof w!="number"||!Number.isFinite(w))throw new Error(`Expected numeric scalar ${g}`);if(S.format!=="float32"&&(!Number.isInteger(w)||w<(S.format==="uint32"?0:-2147483648)||w>(S.format==="uint32"?4294967295:2147483647)))throw new Error(`Scalar ${g} is outside its declared integer format`)}else if(v){if(!(w instanceof j))throw new Error(`Expected GPUVector ${g}`);en(e,w,v.format,v.length,v.chunkLengths)}else throw new Error(`Undeclared binding ${g}`);s.set(g,w)}for(let g of this.operations){g instanceof Ve&&o.values.has(g.input)&&eo(o.values.get(g.input),o.values.get(g.output));for(let E of this.contracts.get(g)?.values??[]){let G=k(E.value);E.access!=="write"&&s.get(G)instanceof j&&y.add(G)}if(!(g instanceof Ie)){let E=this.contracts.get(g);for(let G of E?.values??[]){let C=k(G.value);if(G.access!=="write"&&!s.has(C)&&!o.values.has(C)&&!u.has(C)&&!p.has(C))throw new Error(`Missing ${G.access==="read-write"?"read-write":"execution"} binding ${C}`)}for(let G of E?.values??[]){let C=k(G.value);G.access!=="read"&&this.scalars.some(I=>I.id===C)&&p.add(C)}for(let G of E?.requiredFeatures??[])if(!e.features.has(G))throw new Error(`Operation requires ${G}`);for(let G of E?.values??[]){if(G.access==="read")continue;let C=this.vectors.find(He=>He.id===k(G.value));if(!C)continue;let I=s.get(C.id),F=h.get(C.id)??(I instanceof j?I:void 0),M=G.shape,ce=M&&"like"in M?f(k(M.like)):void 0;if(M&&"like"in M&&!ce)throw new Error(`Missing shape input ${k(M.like)}`);let ee=ce?ce.chunkLengths:M&&"length"in M?M.chunkLengths??C.chunkLengths??[M.length]:C.chunkLengths??(C.length===void 0?void 0:[C.length]);if(G.access==="read-write"&&!(I instanceof j))throw new Error(`Missing read-write binding ${C.id}`);if(G.access==="read-write"&&F!==I)throw new Error(`Read-write target must use its bound storage: ${C.id}`);if(y.has(C.id)&&F!==I)throw new Error(`Output target replaces an earlier read: ${C.id}`);if(!F&&!ee)throw new Error(`Cannot infer length of produced vector ${C.id}`);let je=ee?.reduce((He,st)=>He+st,0)??F.length;if(C.length!==void 0&&C.length!==je||M&&"length"in M&&M.length!==je)throw new Error(`Length constraint failed for ${C.id}`);if(C.chunkLengths&&ee&&(C.chunkLengths.length!==ee.length||C.chunkLengths.some((He,st)=>He!==ee[st])))throw new Error(`Chunk constraint failed for ${C.id}`);F?(en(e,F,C.format,je,ee),wo(C.id,F,s),s.set(C.id,F)):d(C.id,ee,C.format)}continue}let w=this.expressions.find(E=>E.operation===g),S=[];for(let E of w.references){if(s.get(E)===void 0&&!u.has(E)&&!w.gpuScalarInputs.includes(E))throw new Error(`Missing execution binding ${E}`);let C=f(E);C&&this.vectors.some(I=>I.id===E)&&S.push(C)}let v=this.vectors.find(E=>E.id===w.operation.output),T=S[0],b=v?T?.chunkLengths??v.chunkLengths??(v.length===void 0?void 0:[v.length]):[1];if(!b)throw new Error(`Cannot infer length of ${w.operation.output}`);for(let E of S)if(E.chunkLengths.length!==b.length||E.chunkLengths.some((G,C)=>G!==b[C]))throw new Error(`Expression ${w.operation.id} requires matching vector chunk boundaries`);let P=b.reduce((E,G)=>E+G,0);if(v?.length!==void 0&&v.length!==P)throw new Error(`Length constraint failed for ${v.id}`);if(v?.chunkLengths&&(v.chunkLengths.length!==b.length||v.chunkLengths.some((E,G)=>E!==b[G])))throw new Error(`Chunk constraint failed for ${v.id}`);let B=h.get(w.operation.output);B?(en(e,B,w.format,P,b),wo(w.operation.output,B,s),s.set(w.operation.output,B)):d(w.operation.output,b,w.format)}for(let g of Object.keys(n.outputTargets??{})){let w=this.outputs.includes(g)&&this.scalars.some(S=>S.id===g);if(!l.has(g)&&!m.has(g)&&!w&&!this.textures.some(S=>S.id===g&&S.role==="value"))throw new Error(`Unknown graph output target ${g}`)}for(let g of this.outputs)if(!(s.get(g)instanceof j)&&this.scalars.some(w=>w.id===g)){let w=h.get(g);if(w){en(e,w,this.scalars.find(v=>v.id===g).format,1,[1]),wo(g,w,s),s.set(g,w);continue}let S=is(e,g,[1],this.scalars.find(v=>v.id===g).format);a.add(S),s.set(g,S)}return new To(this,s,a,u,o)}catch(g){o.destroy();for(let w of a)w.destroy();throw g}}};function ss(r,e){if(r instanceof q&&(r.type==="composite"||r instanceof it&&!r.predicate)){let t=new Set,n=new Set;for(let i of r.operations){let o=(ss(i,e)?.values??[]).filter(s=>e.some(a=>a.id===k(s.value)));for(let s of o){let a=k(s.value);s.access!=="write"&&!n.has(a)&&t.add(a)}for(let s of o)s.access!=="read"&&n.add(k(s.value))}return{values:[...new Set([...t,...n])].map(i=>({value:i,access:t.has(i)?n.has(i)?"read-write":"read":"write"}))}}return Ee(r)?r.contract:void 0}var To=class{program;values;owned;transientVectors;textures;constructor(e,t,n,i=new Map,o){this.program=e,this.values=t,this.owned=n,this.transientVectors=i,this.textures=o}getOutputs(){let e=Object.create(null);for(let t of this.program.outputs){let n=this.textures?.values.get(t)??this.values.get(t);if(!(n instanceof j||n instanceof ge.Texture||n instanceof ge.TextureView))throw new Error(`Output ${t} has no materialized resource`);e[t]=n}return e}finish(){let e=this.getOutputs();for(let t of Object.values(e))t instanceof j&&this.owned.delete(t);return this.textures?.finish(this.program.outputs),this.destroy(),e}destroy(){this.textures?.destroy();for(let e of this.owned)e.destroy();this.owned.clear()}};function is(r,e,t,n="float32"){let i=[];try{for(let o of t)i.push(new Lt({buffer:r.createBuffer({byteLength:Math.max(1,o)*Z(n).components*4,usage:ge.Buffer.STORAGE|ge.Buffer.VERTEX|ge.Buffer.COPY_SRC|ge.Buffer.COPY_DST}),format:n,length:o,ownsBuffer:!0}));return new j({type:"data",name:e,format:n,data:i,ownsData:!0})}catch(o){for(let s of i)s.destroy();throw o}}function en(r,e,t,n,i){if(e.format!==t||n!==void 0&&e.length!==n)throw new Error(`Incompatible vector ${e.name}`);if(i&&(i.length!==e.data.length||i.some((s,a)=>s!==e.data[a].length)))throw new Error(`Incompatible chunks for ${e.name}`);let o=U(e.format).byteLength;for(let s of e.data)if(s.buffer.device!==r||s.byteStride!==o||s.byteOffset%4!==0||s.rowByteLength!==o)throw new Error(`Expression vector ${e.name} must contain packed 32-bit numeric chunks on the execution device`)}function wo(r,e,t){let n=o=>o.buffer instanceof ge.Buffer?o.buffer:o.buffer.buffer,i=new Map;for(let o of e.data){if(o.length===0)continue;let s=n(o),a=i.get(s)??[];a.push({start:o.byteOffset,end:o.byteOffset+o.length*o.byteStride}),i.set(s,a)}for(let o of i.values())if(o.sort((s,a)=>s.start-a.start),o.some((s,a)=>a>0&&s.start<o[a-1].end))throw new Error(`Output ${r} has overlapping writable chunks`);for(let[o,s]of t)if(o!==r&&s instanceof j&&s.data.some(a=>i.has(n(a))))throw new Error("Expression output targets must not alias inputs or earlier outputs")}var cs=V(R(),1);var Rt={float32:"f32",sint32:"i32",uint32:"u32"};function as(r,e,t,n){if(e===t)return r;let i=Rt;if(t==="float32")return`${i.float32}(${r})`;if(e==="float32"){let s=n==="nearest"?`expression_round_nearest(${r})`:r;return`expression_to_${t}(${s})`}let o=t==="uint32"?`max(${r}, 0)`:`min(${r}, 2147483647u)`;return`${i[t]}(${o})`}var us=`
389
+ }`}var rn=class{props;id;constructor(e){if(this.props=e,this.id=e.id??"gpu-predicate-conjunction",e.inputs.length<2)throw new Error(`${this.id} requires at least two predicates`);let t=e.output.arena;if(e.inputs.some(n=>n.arena!==t))throw new Error(`${this.id} predicates must share one GPUValueArena`)}getCommandNodes(e){let{inputs:t,output:n}=this.props;if(n.arena.graph!==e)throw new Error(`${this.id} predicates must belong to target graph`);let o=n.arena.buffer,i=t.map(a=>`(${Ee(a)} != 0u)`).join(" && "),s=`${pe(0,0)}
390
+ @compute @workgroup_size(1)fn main(){${it(n,`select(0u,1u,${i})`)}}`;return[j({id:this.id,workload:{operation:"GPUPredicateConjunction",commandCount:1,maximumWorkgroupCount:1,maximumInvocationCount:1,readByteLength:t.length*4,writeByteLength:4},resources:[{buffer:o,usage:"storage-write"}],compile:({device:a})=>{let u=new F(a,{id:this.id,source:s,shaderLayout:{bindings:[{name:"gpuValues",type:"storage",group:0,location:0}]}});return{encode:({computePass:c,getBuffer:d})=>{let f={gpuValues:d(o)};u.dispatch(c,{bindings:f,x:1,y:1,z:1})},destroy:()=>u.destroy()}}})]}};var H=class{id;type="composite";operations;metadata;constructor(e){let t=Array.isArray(e)?{operations:e}:e;this.id=t.id??"gpu-composite-operation",this.operations=Object.freeze([...t.operations]),this.metadata=t.metadata}};function Pe(r){let e=r;return typeof e.id=="string"&&typeof e.type=="string"}function vo(r){return r instanceof H?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{},children:Object.freeze(r.operations.map(vo))}):Pe(r)?Object.freeze({id:r.id,type:r.type,...r.metadata?{metadata:r.metadata}:{}}):Object.freeze({id:r.constructor?.name??"gpu-command-node-producer",type:"command-node-producer"})}function fs(r){return typeof r.getCommandNodes=="function"}var Rt=class extends H{type="conditional";predicate;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];super({id:e.id??"gpu-conditional-operation",operations:t,metadata:e.metadata}),this.predicate=Object.freeze({...e.predicate}),this.lowering=e.lowering??"auto"}},st=class extends H{type="loop";predicate;maximumIterations;minimumIterations;lowering;constructor(e){let t=Array.isArray(e.body)?e.body:[e.body];if(super({id:e.id??"gpu-loop-operation",operations:t,metadata:e.metadata}),!Number.isSafeInteger(e.maximumIterations)||e.maximumIterations<1)throw new Error(`${this.id} maximumIterations must be a positive safe integer`);let n=e.minimumIterations??0;if(!Number.isSafeInteger(n)||n<0||n>e.maximumIterations)throw new Error(`${this.id} minimumIterations must be between zero and maximumIterations`);this.predicate=e.predicate?Object.freeze({...e.predicate}):void 0,this.maximumIterations=e.maximumIterations,this.minimumIterations=n,this.lowering=e.lowering??"auto"}};function Mt(r){let e=r.clone(),t=new Map([...e.scalars,...e.vectors,...e.textures].map(i=>[i.id,i])),n=new Set,o=(i,s=!1)=>{if(i instanceof H){for(let a of i.operations)o(a,s||i.type!=="composite");return}if(Pe(i))try{let a=i.contract;if(!a)return;let u=typeof a.outputs=="function"?a.outputs({getValue(d){let f=t.get(d);if(!f)throw new Error(`Undeclared operation value ${d}`);return f instanceof ae?f.descriptor??N.texture({format:f.format,dimension:f.dimension,extent:{width:f.width,height:f.height,depth:f.depth},mipLevels:f.mipLevels,samples:f.samples}):f instanceof Ie?N.scalar(f.format):N.vector(f.format,{length:f.length,chunkLengths:f.chunkLengths})}}):a.outputs;for(let[d,f]of Object.entries(u??{})){if(!a.values.some(h=>h.access==="write"&&k(h.value)===d))throw new Error(`Operation result ${d} requires a write`);if(f.type==="texture"&&f.extent&&"like"in f.extent){let h=f.extent.like;if(!(t.get(h)instanceof ae)||!a.values.some(m=>m.access!=="write"&&k(m.value)===h))throw new Error(`Texture extent source ${h} must be a declared texture read`)}let l=t.get(d);if(l?.role==="input"||l?.role==="state")throw new Error(`Operation result conflicts with ${l.role} ${d}`);if(l){if(l.format!==f.format||l instanceof K!=(f.type==="vector")||l instanceof ae!=(f.type==="texture"))throw new Error(`Incompatible operation result ${d}`);l instanceof K&&f.type==="vector"&&t.set(d,e.constrainResult(l,f))}else{if(s)throw new Error("Operation results inside control flow require explicit declarations");let h=a.values.find(y=>k(y.value)===d&&y.access==="write")?.shape,m=f;if(f.type==="vector"&&f.length===void 0&&h){let y="like"in h?t.get(k(h.like)):void 0,p="length"in h?h:y instanceof K?y:void 0;p?.length!==void 0&&(m={...f,length:p.length,chunkLengths:f.chunkLengths??p.chunkLengths})}let g=e.addDeclaration(d,m,"value");t.set(d,g)}}$t(e,a);for(let d of a.values){let f=k(d.value),l=t.get(f);if(d.access!=="read"&&l?.role==="input")throw new Error(`Cannot write graph input ${f}`);if(d.access!=="write"&&l?.role==="value"&&!n.has(f))throw new Error(`Reads ${f} before it is produced`)}let c=new Set(a.values.filter(d=>d.access!=="read").map(d=>k(d.value)));for(let d of c){if(t.get(d)?.role==="value"&&n.has(d))throw new Error(`Multiple writers for graph result ${d}`);n.add(d)}}catch(a){throw new Error(`${i.id}: ${a instanceof Error?a.message:String(a)}`,{cause:a})}};return e.operations.forEach(i=>o(i)),e}function lr(r,e={}){let t=[];try{r=Mt(r)}catch(i){return{valid:!1,issues:[{level:"error",code:"invalid-operation-contract",message:i instanceof Error?i.message:String(i)}]}}for(let i of r.scalars)i.role==="input"&&e.scalars?.[i.id]===void 0&&t.push({level:"error",code:"missing-input",valueId:i.id,message:`Missing input binding ${i.id}`}),i.role==="value"&&e.scalars?.[i.id]!==void 0&&t.push({level:"error",code:"result-binding",valueId:i.id,message:`Cannot initialize graph result ${i.id}`});let n=new Set(r.scalars.map(i=>i.id));for(let i of r.vectors)i.external&&!e.vectors?.[i.id]&&t.push({level:"error",code:"missing-external-vector",valueId:i.id,message:`External vector "${i.id}" has no WebGPU binding`});let o=i=>{let s="id"in i&&typeof i.id=="string"?i.id:void 0;if(Pe(i))try{let a=i.contract;a&&$t(r,a)}catch(a){t.push({level:"error",code:"invalid-operation-contract",operationId:s,message:`${s}: ${a instanceof Error?a.message:String(a)}`})}if(i instanceof Rt||i instanceof st){let a=i.predicate;a?.source==="gpu"&&(a.value.format!=="uint32"&&t.push({level:"error",code:"invalid-predicate-format",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" must use uint32 state`}),n.has(a.value.id)||t.push({level:"error",code:"missing-predicate-scalar",operationId:s,valueId:a.value.id,message:`GPU predicate "${a.id}" references undeclared scalar "${a.value.id}"`}))}if(i instanceof H)for(let a of i.operations)o(a)};for(let i of r.operations)o(i);return Object.freeze({valid:!t.some(i=>i.level==="error"),issues:Object.freeze(t.map(i=>Object.freeze({...i})))})}var wt=class{device;capabilities;lowerings;compactionIndex=0;constructor(e,t=[]){this.device=e,this.capabilities=Object.freeze({backend:"webgpu",gpuConditionals:!0,nativeLoops:!1,childGraphs:!1});let n=[...this.createCoreLowerings(),...t],o=new Set;for(let i of n){if(!i.type||o.has(i.type))throw new Error(`Duplicate or empty lowering type: ${i.type}`);o.add(i.type)}this.lowerings=Object.freeze(n.map(i=>Object.freeze({type:i.type,lower:i.lower.bind(i)})))}compile(e,t={}){this.compactionIndex=0,e=e.clone();for(let h of e.vectors){let m=t.vectors?.[h.id];if(!h.external||!m||h.chunkLengths)continue;let g="data"in m?m.data:"buffer"in m?[m]:m;e.constrainResult(h,{type:"vector",format:h.format,chunkLengths:g.map(y=>y.length)})}e=Mt(e);let n=new Map,o=(h,m)=>{n.set(h,(n.get(h)??0)|m)},i=h=>{h instanceof H?h.operations.forEach(i):h instanceof Ve?o(h.output,ue.Buffer.COPY_DST):h instanceof Ne&&(o(h.input,ue.Buffer.COPY_SRC),o(h.output,ue.Buffer.COPY_DST))};e.operations.forEach(i);let s=lr(e,t);if(!s.valid)throw new Error(`GPUGraph "${e.id}" validation failed: ${s.issues.filter(h=>h.level==="error").map(h=>h.message).join("; ")}`);let a=new jr(this.device,{id:`${e.id}-commands`}),u=new Map;for(let h of e.scalars)u.set(h.id,wo(a,h.id,h.format));for(let[h,m]of Object.entries(t.scalars??{})){let g=u.get(h);if(!g)throw new Error(`Undeclared scalar binding ${h}`);let y=g.view;a.addCopyPass({id:`${h}-binding`,resources:[{buffer:y,usage:"copy-destination"}],compile:({device:p})=>{let w=g.format==="float32"?new Float32Array([m]):g.format==="uint32"?new Uint32Array([m]):new Int32Array([m]),S=p.createBuffer({data:w,usage:ue.Buffer.COPY_SRC});return{encode:({commandEncoder:v,getBuffer:T})=>v.copyBufferToBuffer({sourceBuffer:S,destinationBuffer:T(y),destinationOffset:y.byteOffset,size:4}),destroy:()=>S.destroy()}}})}let c=new Map;for(let h of e.vectors){if(h.length===void 0)throw new Error(`${h.id}: bind dynamic dimensions through program.compile(device).run(bindings)`);let m;if(h.external){let g=t.vectors[h.id],y="data"in g?g:{format:h.format,length:h.length,data:"buffer"in g?[g]:g};if(m=a.importGPUVector(h.id,y),m.format!==h.format||m.length!==h.length)throw new Error(`${h.id} binding format and length must match its logical vector`);if(h.chunkLengths&&(h.chunkLengths.length!==m.data.length||h.chunkLengths.some((p,w)=>p!==m.data[w].length)))throw new Error(`${h.id} binding must preserve its declared chunk topology`)}else{let g=h.chunkLengths??Fu(h.length,this.device,I(h.format).byteLength),y=g.map((w,S)=>q(a,g.length===1?h.id:`${h.id}-chunk-${S}`,h.format,w,h.role==="value"?ue.Buffer.STORAGE|ue.Buffer.VERTEX|ue.Buffer.COPY_SRC|ue.Buffer.COPY_DST:ue.Buffer.STORAGE|(n.get(h.id)??0))),p=I(h.format);m=new G({id:h.id,name:h.id,format:h.format,length:h.length,valueLength:h.length,stride:p.components,byteStride:p.byteLength,rowByteLength:p.byteLength,data:y})}c.set(h.id,m)}let d=new Map,f=new Map;for(let h of e.textures){(0,ue.assert)(h.width!==void 0&&h.height!==void 0);let m=t.textures?.[h.id],g={...h,width:h.width,height:h.height};if(m instanceof ue.TextureView){let p=Q(m);(0,ue.assert)(p.format===h.format&&p.width===h.width&&p.height===h.height),f.set(h.id,m),m=p.texture,g={...g,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples}}let y=h.external?a.importTexture(g,m):a.createTransientTexture(g);d.set(h.id,y)}let l={path:[],nodes:[],decisions:[],predicates:[],scalars:u,vectors:c,textures:d,textureValues:e.textures,textureViews:f,predicateConjunctions:new Map,commandNodeIds:new Set,transientResultNames:new Set(e.vectors.filter(h=>h.role==="value"&&!h.external).map(h=>h.id)),retainedBuffers:[]};for(let h of e.operations)this.lower(a,h,l);return Object.freeze({program:e,graph:a,scalars:u,vectors:c,textures:d,validation:s,lowering:Object.freeze({operations:e.operationTree,nodes:Object.freeze(l.nodes.map(h=>Object.freeze({...h,operationPath:Object.freeze([...h.operationPath])}))),decisions:Object.freeze(l.decisions.map(h=>Object.freeze({...h})))})})}createCoreLowerings(){return[{type:"vector-upload",lower:Wi},{type:"vector-copy",lower:Hi},{type:"compaction",lower:(e,t)=>{let{input:n,flags:o,output:i,count:s}=e.props;t.graph.add(new zr({id:`${e.id}-${this.compactionIndex++}`,input:t.resolveVector(n),flags:t.resolveVector(o),output:t.resolveVector(i),count:t.resolveScalar(s).view}))}},{type:"scalar-literal",lower:(e,t)=>{let n=new At({id:e.id,output:t.resolveScalar(e.props.output),value:e.props.value});this.emitProducer(t.graph,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-literal",reason:"host-known literal lowers to one compute command node"})}},{type:"scalar-operation",lower:(e,t)=>{let n=new Yr({id:e.id,operation:e.operation,left:t.resolveScalar(e.left),right:e.right?t.resolveScalar(e.right):void 0,output:t.resolveScalar(e.output)});this.emitProducer(t.graph,n,[[1,1,1]]),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-scalar-kernel",reason:"scalar operation lowers to one compute command node"})}},{type:"vector-madd",lower:(e,t)=>{let n=e.props,o=new Kr({id:e.id,input:t.resolveVector(n.input),scale:t.resolveScalar(n.scale),addend:t.resolveVector(n.addend),output:t.resolveVector(n.output)});this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-vector-madd",reason:"dense float32 MADD lowers through explicit command nodes"})}},{type:"dot-product",lower:(e,t)=>{let n=e.props,o=new Zr({id:e.id,left:t.resolveVector(n.left),right:t.resolveVector(n.right),output:t.resolveScalar(n.output)});this.emitProducer(t.graph,o),t.recordDecision({operationId:e.id,operationType:e.type,lowering:"webgpu-hierarchical-dot",reason:"chunk dot products use bounded hierarchical reductions into the scalar arena"})}},{type:"spmv",lower:(e,t)=>{let n=e.props,o=n.matrix,i=new tn({id:e.id,rowOffsets:t.resolveVector(o.rowOffsets),columnIndices:t.resolveVector(o.columnIndices),values:t.resolveVector(o.values),vector:t.resolveVector(n.vector),output:t.resolveVector(n.output),columns:o.columns,statistics:o.statistics,strategy:n.strategy}),s=i.getStrategy(t.graph);this.emitProducer(t.graph,i),t.recordDecision({operationId:e.id,operationType:e.type,lowering:`webgpu-spmv:${s.id}`,reason:s.reason})}},{type:"conditional",lower:(e,t)=>{t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-indirect-gate",reason:"WebGPU realizes runtime predicates with zero/nonzero indirect dispatch"});for(let n of e.operations)t.lowerConditional(e.predicate,n)}},{type:"loop",lower:(e,t)=>{if(!e.predicate||e.lowering==="unroll"){t.recordDecision({operationId:e.id,operationType:e.type,lowering:"bounded-unroll",reason:e.predicate?"explicit unroll preference":"loop has no runtime predicate"});for(let n=0;n<e.maximumIterations;n++)for(let o of e.operations)t.lower(o);return}t.recordDecision({operationId:e.id,operationType:e.type,lowering:"gpu-gated-bounded-sequence",reason:"WebGPU has indirect dispatch but no native graph loop"});for(let n=0;n<e.maximumIterations;n++){let o=n>=e.minimumIterations;for(let i of e.operations)o?t.lowerConditional(e.predicate,i):t.lower(i)}}}]}lower(e,t,n){let o="id"in t&&typeof t.id=="string"?t.id:t.constructor?.name??"command-node-producer";n.path.push(o);let i=n.retainedBuffers,s=[...i];if(Pe(t))for(let a of t.contract?.values??[]){let u=typeof a.value=="string"?a.value:a.value.id;if(n.transientResultNames.has(u))for(let c of n.vectors.get(u).data)s.push(c.buffer)}n.retainedBuffers=s;try{if(t instanceof H&&t.type==="composite"){n.decisions.push({operationId:t.id,operationType:t.type,lowering:"flatten",reason:"WebGPU has no executable child-graph primitive"});for(let a of t.operations)this.lower(e,a,n);return}if(Pe(t)){for(let u of t.contract?.requiredFeatures??[])if(!this.device.features.has(u))throw new Error(`${o} requires ${u}`);let a=this.lowerings.find(u=>u.type===t.type)?.lower;if(a){let u=()=>(t instanceof Ne&&n.textureValues.some(c=>c.id===t.input)?qi:a)(t,{graph:e,capabilities:this.capabilities,lower:c=>this.lower(e,c,n),lowerConditional:(c,d)=>{n.predicates.push(c);try{this.lower(e,d,n)}finally{n.predicates.pop()}},resolveScalar:c=>this.resolveScalar(c,n),resolveVector:c=>this.resolveVector(c,n),resolveTexture:c=>this.resolveTexture(c,n),resolveTextureView:c=>{let d=c instanceof Ue?c.texture:c,f=c instanceof Ue?c.props:{},l=n.textureViews.get(typeof d=="string"?d:d.id);return e.createTextureView(this.resolveTexture(d,n),l?Ni(l,f):f)},recordDecision:c=>n.decisions.push(c)});t instanceof Rt||t instanceof st?u():this.withNodeDecoration(e,n,u);return}}if("getNodes"in t||fs(t)){n.decisions.push({operationId:o,operationType:"command-node-producer",lowering:"explicit-command-nodes",reason:"execution primitive constructs explicit command nodes"}),this.withNodeDecoration(e,n,()=>e.add(t));return}throw new Error(`GPUGraph operation "${o}" has no WebGPU lowering`)}finally{n.retainedBuffers=i,n.path.pop()}}emitProducer(e,t,n){let o=t.getCommandNodes(e);if(!n){Me(e,o);return}if(o.length!==n.length)throw new Error(`lowering produced ${o.length} command nodes but declared ${n.length} dispatches`);let i=o.map((s,a)=>this.attachDispatch(s,n[a]));Me(e,i)}attachDispatch(e,t){if(e.type!=="compute")throw new Error(`dispatch geometry can only be attached to compute command nodes; got ${e.type} node "${e.id}"`);return W(e,t)}withNodeDecoration(e,t,n){return e.withComputeLowering(o=>this.decorateComputeNode(e,o,t),()=>e.withOtherLowering(o=>{if(t.predicates.length)throw new Error(`GPU predicates do not support ${o.type} node "${o.id}"`);let i=this.makeCommandNodeIdUnique(o,t);return t.nodes.push({nodeId:i.id,nodeType:i.type,operationPath:[...t.path]}),{...i,retainedBuffers:t.retainedBuffers}},n))}decorateComputeNode(e,t,n){if(t={...this.makeCommandNodeIdUnique(t,n),retainedBuffers:n.retainedBuffers},n.path.length&&n.nodes.push({nodeId:t.id,nodeType:"compute",operationPath:[...n.path]}),!n.predicates.length)return t;if(t.condition)throw new Error(`compute node "${t.id}" already has condition`);let o=Vr(t);if(!o)throw new Error(`compute node "${t.id}" under runtime predicate must declare exact dispatch geometry`);let i;if(n.predicates.length===1)i=n.scalars.get(n.predicates[0].value.id);else{let u=n.predicates.map(l=>l.value.id).join("&&"),c=n.predicateConjunctions.get(u);c||(c=wo(e,`predicate-and-${n.predicateConjunctions.size}`,"uint32"),n.predicateConjunctions.set(u,c));let d=n.predicates.map(l=>n.scalars.get(l.value.id)),f=new rn({id:`${t.id}-predicate-and`,inputs:d,output:c}).getCommandNodes(e).map(l=>this.attachDispatch(l,[1,1,1]));e.withoutComputeLowering(()=>Me(e,f)),i=c}if(!i)throw new Error(`runtime predicate for "${t.id}" could not be resolved`);let s=new fr(e,{id:`${t.id}-predicate`,active:i,workgroups:o}),a=s.getUpdateCommandNodes(e,`${t.id}-predicate-update`).map(u=>this.attachDispatch(u,[1,1,1]));return e.withoutComputeLowering(()=>Me(e,a)),{...t,condition:s.condition}}makeCommandNodeIdUnique(e,t){if(!t.commandNodeIds.has(e.id))return t.commandNodeIds.add(e.id),e;let n=1,o=`${e.id}-iteration-${n}`;for(;t.commandNodeIds.has(o);)n++,o=`${e.id}-iteration-${n}`;return t.commandNodeIds.add(o),{...e,id:o}}resolveTexture(e,t){let n=typeof e=="string"?e:e.id;if(typeof e=="string"?!t.textures.has(n):!t.textureValues.includes(e))throw new Error(`Undeclared program texture "${n}"`);return t.textures.get(n)}resolveScalar(e,t){let n=typeof e=="string"?e:e.id,o=t.scalars.get(n);if(!o||typeof e!="string"&&o.format!==e.format)throw new Error(`GPUGraph scalar "${n}" is not part of compilation`);return o}resolveVector(e,t){let n=typeof e=="string"?e:e.id,o=t.vectors.get(n);if(!o||typeof e!="string"&&(o.format!==e.format||e.length!==void 0&&o.length!==e.length))throw new Error(`GPUGraph vector "${n}" is not part of compilation`);return o}};function Fu(r,e,t){let n=Math.floor(e.limits.maxStorageBufferBindingSize/t);if(n<1||r<=n)return[r];let o=[];for(let i=0;i<r;i+=n)o.push(Math.min(n,r-i));return o}var ye=R(A(),1);var Tt=R(A(),1);var at=class{type="shader-pass";id;fragmentSource;inputs;samplers;parameters;output;outputDescriptor;constructor(e){this.id=e.id??`${e.output}-shader-pass`,this.fragmentSource=e.fragmentSource,this.inputs=Object.freeze({...e.inputs}),this.parameters=Object.freeze({...e.parameters}),this.samplers=Object.freeze(Object.fromEntries(Object.entries(e.samplers??{}).map(([o,i])=>[o,Object.freeze({...i})]))),this.output=e.output;let t=e.outputDescriptor;(0,Tt.assert)(t.extent&&(t.dimension??"2d")==="2d"&&(t.mipLevels??1)===1&&(t.samples??1)===1),this.outputDescriptor=N.texture({...t,dimension:"2d",mipLevels:1,samples:1});let n=[...Object.keys(this.inputs),...Object.keys(this.samplers)];(0,Tt.assert)(new Set(n).size===n.length);for(let o of[...n,...Object.keys(this.parameters)])(0,Tt.assert)(/^[A-Za-z][A-Za-z0-9_]*$/.test(o)&&!["parameters","shade","vertexMain","fragmentMain"].includes(o)&&!o.startsWith("GraphShaderPass"));for(let o of Object.values(this.samplers))(0,Tt.assert)((o.type??"color-sampler")==="color-sampler")}get contract(){return{values:[...Object.values(this.inputs).map(e=>({value:e,access:"read",textureUsage:"sampled"})),...Object.values(this.parameters).map(e=>({value:e,access:"read"})),{value:this.output,access:"write",textureUsage:"render-attachment"}],outputs:({getValue:e})=>{for(let t of Object.values(this.inputs)){let n=e(t);(0,Tt.assert)(n.type==="texture"&&(n.dimension??"2d")==="2d"&&(n.samples??1)===1)}for(let t of Object.values(this.parameters))(0,Tt.assert)(e(t).type==="scalar");return{[this.output]:this.outputDescriptor}}}}};var Ru=class{add(r,e,t){if(typeof arguments[0]!="string")for(let n in arguments[0])this.add(n,arguments[0][n],arguments[1]);else(Array.isArray(r)?r:[r]).forEach(function(n){this[n]=this[n]||[],e&&this[n][t?"unshift":"push"](e)},this)}run(r,e){this[r]=this[r]||[],this[r].forEach(function(t){t.call(e&&e.context?e.context:e,e)})}},Mu=class{constructor(r){this.jsep=r,this.registered={}}register(...r){r.forEach(e=>{if(typeof e!="object"||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)})}},ge=class x{static get version(){return"1.4.0"}static toString(){return"JavaScript Expression Parser (JSEP) v"+x.version}static addUnaryOp(e){return x.max_unop_len=Math.max(e.length,x.max_unop_len),x.unary_ops[e]=1,x}static addBinaryOp(e,t,n){return x.max_binop_len=Math.max(e.length,x.max_binop_len),x.binary_ops[e]=t,n?x.right_associative.add(e):x.right_associative.delete(e),x}static addIdentifierChar(e){return x.additional_identifier_chars.add(e),x}static addLiteral(e,t){return x.literals[e]=t,x}static removeUnaryOp(e){return delete x.unary_ops[e],e.length===x.max_unop_len&&(x.max_unop_len=x.getMaxKeyLen(x.unary_ops)),x}static removeAllUnaryOps(){return x.unary_ops={},x.max_unop_len=0,x}static removeIdentifierChar(e){return x.additional_identifier_chars.delete(e),x}static removeBinaryOp(e){return delete x.binary_ops[e],e.length===x.max_binop_len&&(x.max_binop_len=x.getMaxKeyLen(x.binary_ops)),x.right_associative.delete(e),x}static removeAllBinaryOps(){return x.binary_ops={},x.max_binop_len=0,x}static removeLiteral(e){return delete x.literals[e],x}static removeAllLiterals(){return x.literals={},x}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new x(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map(t=>t.length))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return x.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!x.binary_ops[String.fromCharCode(e)]||x.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return x.isIdentifierStart(e)||x.isDecimalDigit(e)}throwError(e){let t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(x.hooks[e]){let n={context:this,node:t};return x.hooks.run(e,n),n.node}return t}searchHook(e){if(x.hooks[e]){let t={context:this};return x.hooks[e].find(function(n){return n.call(t.context,t),t.node}),t.node}}gobbleSpaces(){let e=this.code;for(;e===x.SPACE_CODE||e===x.TAB_CODE||e===x.LF_CODE||e===x.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");let e=this.gobbleExpressions(),t=e.length===1?e[0]:{type:x.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t=[],n,o;for(;this.index<this.expr.length;)if(n=this.code,n===x.SEMCOL_CODE||n===x.COMMA_CODE)this.index++;else if(o=this.gobbleExpression())t.push(o);else if(this.index<this.expr.length){if(n===e)break;this.throwError('Unexpected "'+this.char+'"')}return t}gobbleExpression(){let e=this.searchHook("gobble-expression")||this.gobbleBinaryExpression();return this.gobbleSpaces(),this.runHook("after-expression",e)}gobbleBinaryOp(){this.gobbleSpaces();let e=this.expr.substr(this.index,x.max_binop_len),t=e.length;for(;t>0;){if(x.binary_ops.hasOwnProperty(e)&&(!x.isIdentifierStart(this.code)||this.index+e.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+e.length))))return this.index+=t,e;e=e.substr(0,--t)}return!1}gobbleBinaryExpression(){let e,t,n,o,i,s,a,u,c;if(s=this.gobbleToken(),!s||(t=this.gobbleBinaryOp(),!t))return s;for(i={value:t,prec:x.binaryPrecedence(t),right_a:x.right_associative.has(t)},a=this.gobbleToken(),a||this.throwError("Expected expression after "+t),o=[s,i,a];t=this.gobbleBinaryOp();){if(n=x.binaryPrecedence(t),n===0){this.index-=t.length;break}i={value:t,prec:n,right_a:x.right_associative.has(t)},c=t;let d=f=>i.right_a&&f.right_a?n>f.prec:n<=f.prec;for(;o.length>2&&d(o[o.length-2]);)a=o.pop(),t=o.pop().value,s=o.pop(),e={type:x.BINARY_EXP,operator:t,left:s,right:a},o.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+c),o.push(i,e)}for(u=o.length-1,e=o[u];u>1;)e={type:x.BINARY_EXP,operator:o[u-1].value,left:o[u-2],right:e},u-=2;return e}gobbleToken(){let e,t,n,o;if(this.gobbleSpaces(),o=this.searchHook("gobble-token"),o)return this.runHook("after-token",o);if(e=this.code,x.isDecimalDigit(e)||e===x.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===x.SQUOTE_CODE||e===x.DQUOTE_CODE)o=this.gobbleStringLiteral();else if(e===x.OBRACK_CODE)o=this.gobbleArray();else{for(t=this.expr.substr(this.index,x.max_unop_len),n=t.length;n>0;){if(x.unary_ops.hasOwnProperty(t)&&(!x.isIdentifierStart(this.code)||this.index+t.length<this.expr.length&&!x.isIdentifierPart(this.expr.charCodeAt(this.index+t.length)))){this.index+=n;let i=this.gobbleToken();return i||this.throwError("missing unaryOp argument"),this.runHook("after-token",{type:x.UNARY_EXP,operator:t,argument:i,prefix:!0})}t=t.substr(0,--n)}x.isIdentifierStart(e)?(o=this.gobbleIdentifier(),x.literals.hasOwnProperty(o.name)?o={type:x.LITERAL,value:x.literals[o.name],raw:o.name}:o.name===x.this_str&&(o={type:x.THIS_EXP})):e===x.OPAREN_CODE&&(o=this.gobbleGroup())}return o?(o=this.gobbleTokenProperty(o),this.runHook("after-token",o)):this.runHook("after-token",!1)}gobbleTokenProperty(e){this.gobbleSpaces();let t=this.code;for(;t===x.PERIOD_CODE||t===x.OBRACK_CODE||t===x.OPAREN_CODE||t===x.QUMARK_CODE;){let n;if(t===x.QUMARK_CODE){if(this.expr.charCodeAt(this.index+1)!==x.PERIOD_CODE)break;n=!0,this.index+=2,this.gobbleSpaces(),t=this.code}this.index++,t===x.OBRACK_CODE?(e={type:x.MEMBER_EXP,computed:!0,object:e,property:this.gobbleExpression()},e.property||this.throwError('Unexpected "'+this.char+'"'),this.gobbleSpaces(),t=this.code,t!==x.CBRACK_CODE&&this.throwError("Unclosed ["),this.index++):t===x.OPAREN_CODE?e={type:x.CALL_EXP,arguments:this.gobbleArguments(x.CPAREN_CODE),callee:e}:(t===x.PERIOD_CODE||n)&&(n&&this.index--,this.gobbleSpaces(),e={type:x.MEMBER_EXP,computed:!1,object:e,property:this.gobbleIdentifier()}),n&&(e.optional=!0),this.gobbleSpaces(),t=this.code}return e}gobbleNumericLiteral(){let e="",t,n;for(;x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(this.code===x.PERIOD_CODE)for(e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);if(t=this.char,t==="e"||t==="E"){for(e+=this.expr.charAt(this.index++),t=this.char,(t==="+"||t==="-")&&(e+=this.expr.charAt(this.index++));x.isDecimalDigit(this.code);)e+=this.expr.charAt(this.index++);x.isDecimalDigit(this.expr.charCodeAt(this.index-1))||this.throwError("Expected exponent ("+e+this.char+")")}return n=this.code,x.isIdentifierStart(n)?this.throwError("Variable names cannot start with a number ("+e+this.char+")"):(n===x.PERIOD_CODE||e.length===1&&e.charCodeAt(0)===x.PERIOD_CODE)&&this.throwError("Unexpected period"),{type:x.LITERAL,value:parseFloat(e),raw:e}}gobbleStringLiteral(){let e="",t=this.index,n=this.expr.charAt(this.index++),o=!1;for(;this.index<this.expr.length;){let i=this.expr.charAt(this.index++);if(i===n){o=!0;break}else if(i==="\\")switch(i=this.expr.charAt(this.index++),i){case"n":e+=`
391
+ `;break;case"r":e+="\r";break;case"t":e+=" ";break;case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:e+=i}else e+=i}return o||this.throwError('Unclosed quote after "'+e+'"'),{type:x.LITERAL,value:e,raw:this.expr.substring(t,this.index)}}gobbleIdentifier(){let e=this.code,t=this.index;for(x.isIdentifierStart(e)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(e=this.code,x.isIdentifierPart(e));)this.index++;return{type:x.IDENTIFIER,name:this.expr.slice(t,this.index)}}gobbleArguments(e){let t=[],n=!1,o=0;for(;this.index<this.expr.length;){this.gobbleSpaces();let i=this.code;if(i===e){n=!0,this.index++,e===x.CPAREN_CODE&&o&&o>=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}else if(i===x.COMMA_CODE){if(this.index++,o++,o!==t.length){if(e===x.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===x.CBRACK_CODE)for(let s=t.length;s<o;s++)t.push(null)}}else if(t.length!==o&&o!==0)this.throwError("Expected comma");else{let s=this.gobbleExpression();(!s||s.type===x.COMPOUND)&&this.throwError("Expected comma"),t.push(s)}}return n||this.throwError("Expected "+String.fromCharCode(e)),t}gobbleGroup(){this.index++;let e=this.gobbleExpressions(x.CPAREN_CODE);if(this.code===x.CPAREN_CODE)return this.index++,e.length===1?e[0]:e.length?{type:x.SEQUENCE_EXP,expressions:e}:!1;this.throwError("Unclosed (")}gobbleArray(){return this.index++,{type:x.ARRAY_EXP,elements:this.gobbleArguments(x.CBRACK_CODE)}}},Vu=new Ru;Object.assign(ge,{hooks:Vu,plugins:new Mu(ge),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"??":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10,"**":11},right_associative:new Set(["**"]),additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"});ge.max_unop_len=ge.getMaxKeyLen(ge.unary_ops);ge.max_binop_len=ge.getMaxKeyLen(ge.binary_ops);var hr=r=>new ge(r).parse(),Nu=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(ge).filter(r=>!Nu.includes(r)&&hr[r]===void 0).forEach(r=>{hr[r]=ge[r]});hr.Jsep=ge;var zu="ConditionalExpression",ju={name:"ternary",init(r){r.hooks.add("after-expression",function(t){if(t.node&&this.code===r.QUMARK_CODE){this.index++;let n=t.node,o=this.gobbleExpression();if(o||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===r.COLON_CODE){this.index++;let i=this.gobbleExpression();if(i||this.throwError("Expected expression"),t.node={type:zu,test:n,consequent:o,alternate:i},n.operator&&r.binary_ops[n.operator]<=.9){let s=n;for(;s.right.operator&&r.binary_ops[s.right.operator]<=.9;)s=s.right;t.node.test=s.right,s.right=t.node,t.node=n}}else this.throwError("Expected :")}})}};hr.plugins.register(ju);var ls=hr;var Wu=ls;function So(r){return typeof r=="string"?Wu(r):r}var $e=class{get contract(){let e=nn(this.expression),t=on(e);return{outputs:({getValue:n})=>{let o=t.map(a=>{let u=n(a);if(u.type==="texture")throw new Error("Numeric expressions cannot read textures");return[a,u]}),i=fe(e,new Map(o.map(([a,u])=>[a,u.format]))),s=o.some(([,a])=>a.type==="vector");return{[this.output]:s||!hs(i)?N.vector(i,s?{}:{length:1}):N.scalar(i)}},values:[...on(nn(this.expression)).map(n=>({value:n,access:"read"})),{value:this.output,access:"write"}]}}type="expression";id;output;expression;integerRounding;constructor(e){this.id=e.id??`${e.output}-expression`,this.output=e.output,this.expression=e.expression,this.integerRounding=e.integerRounding??"truncate"}};function Eo(r){return/^(float32|sint32|uint32)(x[234])?$/.test(r)}function J(r){let e=I(r);return{components:e.components,componentType:e.signedDataType}}function mr(r,e){return e===1?r:`${r}x${e}`}function nn(r){let e=t=>{let n=t;switch(n.type){case"Identifier":return{kind:"reference",name:n.name};case"Literal":if(typeof n.value=="number"&&Number.isFinite(Math.fround(n.value)))return{kind:"literal",value:n.value};break;case"UnaryExpression":if(n.operator==="-")return{kind:"negate",argument:e(n.argument)};break;case"MemberExpression":{let o=n.property;if(n.computed||o.type!=="Identifier")throw new Error("Computed component access is unsupported");if(!/^[xyzw]{1,4}$/.test(o.name))throw new Error(`Invalid swizzle .${o.name}: expected 1\u20134 xyzw components`);return{kind:"swizzle",argument:e(n.object),components:[...o.name].map(i=>"xyzw".indexOf(i))}}case"CallExpression":{let o=n.callee;if(o.type!=="Identifier")break;let i=o.name;if(/^vec[234]$/.test(i)){if(n.arguments.length<1||n.arguments.length>4)throw new Error(`${i}: expected 1\u20134 arguments, received ${n.arguments.length}`);return{kind:"construct",width:Number(i[3]),arguments:n.arguments.map(e)}}if(hs(i)){if(n.arguments.length!==1)throw new Error(`Invalid argument count for ${i}`);return{kind:"cast",format:i,argument:e(n.arguments[0])}}if(!["abs","sqrt","pow","sin","cos","tan","exp","log","dot","length","equalAll","select"].includes(i))break;let s=i==="select"?3:["pow","dot","equalAll"].includes(i)?2:1;if(n.arguments.length!==s)throw new Error(`Invalid argument count for GPU expression function ${i}`);return{kind:"call",name:i,arguments:n.arguments.map(e)}}case"BinaryExpression":if(["+","-","*","/"].includes(n.operator))return{kind:"binary",operator:n.operator,left:e(n.left),right:e(n.right)};break}throw new Error(`Unsupported GPU expression syntax: ${n.type}`)};return e(typeof r=="string"?So(r):r)}function on(r){let e=new Set,t=n=>{switch(n.kind){case"reference":e.add(n.name);break;case"swizzle":case"cast":case"negate":t(n.argument);break;case"construct":case"call":n.arguments.forEach(t);break;case"binary":t(n.left),t(n.right);break}};return t(r),[...e]}function hs(r){return r==="float32"||r==="sint32"||r==="uint32"}function fe(r,e){switch(r.kind){case"literal":return"float32";case"reference":{let t=e.get(r.name);if(!t)throw new Error(`Undeclared numeric input ${r.name}`);return t}case"swizzle":{let t=J(fe(r.argument,e)),n=Math.max(...r.components)+1;if(n>t.components){let o=r.components.map(s=>"xyzw"[s]).join(""),i=r.argument.kind==="reference"?r.argument.name:"input";throw new Error(`.${o} needs ${n} components; ${i} has ${t.components}`)}return mr(t.componentType,r.components.length)}case"construct":{let t=r.arguments.map(i=>J(fe(i,e))),n=t[0].componentType;if(t.some(i=>i.componentType!==n))throw new Error(`vec${r.width}: mixed component types (${t.map(i=>i.componentType).join(", ")})`);let o=t.reduce((i,s)=>i+s.components,0);if(!(t.length===1&&o===1)&&o!==r.width)throw new Error(`vec${r.width}(...) needs ${r.width} components; received ${o}`);return mr(n,r.width)}case"cast":return mr(r.format,J(fe(r.argument,e)).components);default:{let n=(r.kind==="call"?r.arguments:r.kind==="negate"?[r.argument]:[r.left,r.right]).map(i=>J(fe(i,e)));if(r.kind==="call"){let[i,s,a]=n;if(r.name==="equalAll"){if(i.componentType!==s.componentType||i.components!==s.components)throw new Error("equalAll requires matching types and row widths");return"uint32"}if(r.name==="select"){if(s.componentType!==a.componentType)throw new Error("select branches require matching component types");let u=Math.max(s.components,a.components);if(n.some(c=>c.components!==1&&c.components!==u))throw new Error("select widths must match its branches or be one component");return mr(s.componentType,u)}if(r.name==="dot"&&i.components!==s.components)throw new Error("dot requires matching row widths")}if(n.some(i=>i.componentType!=="float32"))throw new Error("Arithmetic requires float32 operands; use an explicit float32 cast");if(r.kind==="call"&&(r.name==="dot"||r.name==="length"))return"float32";let o=Math.max(...n.map(i=>i.components));if(n.some(i=>i.components!==1&&i.components!==o))throw new Error("Expression row widths must match or broadcast from one component");return mr("float32",o)}}}var Vt=class{contracts=new Map;resultNames;expressions;operations;outputs;scalars;vectors;textures;constructor(e,t={}){e=Mt(e),this.scalars=e.scalars,this.vectors=e.vectors,this.textures=e.textures;let n=[],o=m=>{if(m instanceof H&&m.type==="composite")m.operations.forEach(o);else{if(m instanceof H){let g=p=>p instanceof at||p instanceof H&&p.operations.some(g);if(m.operations.some(g))throw new Error("Shader-pass operations inside control flow are not supported");let y=p=>p instanceof $e||p instanceof H&&p.operations.some(y);if(m.operations.some(y))throw new Error("Expression operations inside control flow are not supported")}n.push(m)}};e.operations.forEach(o),this.operations=n;let i=new Map([...this.scalars,...this.vectors,...this.textures].map(m=>[m.id,m])),s=n.filter(m=>m instanceof $e),a=new Set,u=new Map;for(let m of n)if(m instanceof $e&&u.set(m,new Set(a)),!!Pe(m))try{let g=ps(m,this.scalars);if(!g)continue;$t(e,g),this.contracts.set(m,g);for(let y of g.values){let p=k(y.value);y.access!=="read"&&this.scalars.some(w=>w.id===p)&&a.add(p)}}catch(g){throw new Error(`${m.id}: ${g instanceof Error?g.message:String(g)}`,{cause:g})}let c=new Set;for(let m of s){if(c.has(m.output))throw new Error(`Multiple expression writers for ${m.output}`);c.add(m.output)}let d=new Set([...i.keys()].filter(m=>!c.has(m)&&i.get(m)?.role!=="value")),f=[];for(let m of n){let g=this.contracts.get(m);if(!(m instanceof $e)){for(let y of g?.values??[]){let p=k(y.value);if(y.access!=="write"&&!d.has(p))throw new Error(`${"id"in m?m.id:"Operation"}: Reads ${p} before it is produced`)}for(let y of g?.values??[])y.access!=="read"&&d.add(k(y.value));continue}try{let y=i.get(m.output);if(!y||!Eo(y.format))throw new Error(`Expression output ${m.output} must declare a 32-bit numeric row of width 1\u20134`);let p=nn(m.expression),w=on(p);if(w.includes(m.output))throw new Error(`Reads ${m.output} before it is produced`);let S=new Map;for(let b of w){let P=i.get(b);if(!P||!Eo(P.format))throw new Error(`Expression input ${b} must declare a 32-bit numeric row of width 1\u20134`);if(S.set(b,P.format),!d.has(b))throw new Error(`Reads ${b} before it is produced`)}if(this.scalars.some(b=>b.id===y.id)&&w.some(b=>this.vectors.some(P=>P.id===b)))throw new Error(`Vector expression cannot write scalar ${m.output}`);if(this.vectors.some(b=>b.id===m.output)&&!w.some(b=>this.vectors.some(P=>P.id===b))&&!(y instanceof K&&y.role==="value"&&y.length!==void 0))throw new Error(`Vector expression ${m.output} requires a vector input to determine its shape`);let v=fe(p,S);if(y.format!==v)throw new Error("Expression result type must match its output declaration");d.add(m.output);let T=w.filter(b=>u.get(m).has(b));f.push({operation:m,expression:p,format:v,formats:S,references:w,gpuScalarInputs:T})}catch(y){throw y instanceof Error?new Error(`${m.id}: ${y.message}`,{cause:y}):y}}this.expressions=f;let l=[...i.values()].filter(m=>m.role==="value");this.resultNames=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(g=>g.access!=="read").map(g=>k(g.value))).filter(m=>i.get(m)?.role!=="input"&&i.get(m)?.role!=="state"));let h=new Set([...this.contracts.values()].flatMap(m=>m.values.filter(g=>g.access!=="write").map(g=>k(g.value))));this.outputs=[...t.outputs??(l.length?[...this.resultNames].filter(m=>!h.has(m)):s.map(m=>m.output))];for(let m of this.outputs){if(!i.has(m))throw new Error(`Undeclared output ${m}`);if(this.scalars.some(g=>g.id===m)&&!c.has(m)&&!a.has(m))throw new Error(`Selected scalar ${m} must be produced by a graph operation`)}}resolveBindings(e,t={}){let n=[...this.scalars,...this.vectors,...this.textures];if(!(n.some(c=>c.role==="input"||c.role==="state")||Object.values(e).some(c=>c!==void 0&&typeof c=="object"&&!(c instanceof z)&&!(c instanceof Te)&&!(c instanceof ye.Texture)&&!(c instanceof ye.TextureView)))){for(let c of Object.keys(e))if(n.find(d=>d.id===c)?.role==="value")throw new Error(`Use outputTargets for graph result ${c}`);return{bindings:e,options:t}}for(let c of Object.keys(e))if(!["inputs","state","outputTargets"].includes(c))throw new Error(`Unknown execution option ${c}`);let s=e,a=Object.create(null);for(let[c,d]of[["input",s.inputs],["state",s.state]])for(let[f,l]of Object.entries(d??{})){let h=n.find(g=>g.id===f),m=h?.role??(this.resultNames.has(f)?"value":"input");if(!h||m!==c)throw new Error(`Invalid ${c} binding ${f}`);a[f]=l}for(let c of n)if((c.role==="input"||c.role==="state")&&a[c.id]===void 0)throw new Error(`Missing ${c.role} binding ${c.id}`);if(t.outputTargets&&s.outputTargets)throw new Error("Duplicate output targets");let u=s.outputTargets??t.outputTargets;for(let c of Object.keys(u??{}))if(!this.resultNames.has(c)||!this.outputs.includes(c))throw new Error(`Invalid graph output target ${c}`);return{bindings:a,options:{outputTargets:u}}}prepare(e,t,n={},o=!1){let i=new Mr(e,this.textures,[...this.contracts.values()],t,n.outputTargets??{}),s=new Map,a=new Set,u=new Map,c=o&&!this.operations.some(p=>p instanceof H),d=p=>{let w=s.get(p);return w instanceof z?{length:w.length,chunkLengths:w.data.map(S=>S.length)}:u.get(p)},f=(p,w,S)=>{if(c&&!this.outputs.includes(p)&&this.vectors.some(v=>v.id===p&&v.role==="value"))u.set(p,{length:w.reduce((v,T)=>v+T,0),chunkLengths:w});else{let v=ms(e,p,w,S);a.add(v),s.set(p,v)}},l=new Set(this.expressions.map(p=>p.operation.output)),h=new Map;for(let[p,w]of Object.entries(n.outputTargets??{}))if(!this.textures.some(S=>S.id===p)){if(!(w instanceof z))throw i.destroy(),new Error(`Expected GPUVector ${p}`);h.set(p,w)}let m=new Set([...this.contracts.values()].flatMap(p=>p.values.filter(w=>w.access!=="read"&&this.vectors.some(S=>S.id===k(w.value))).map(w=>k(w.value)))),g=new Set,y=new Set;try{for(let[p,w]of Object.entries(t)){if(this.textures.some(T=>T.id===p))continue;if(l.has(p))throw new Error(`Use outputTargets for expression output ${p}`);let S=this.scalars.find(T=>T.id===p),v=this.vectors.find(T=>T.id===p);if(S){if(typeof w!="number"||!Number.isFinite(w))throw new Error(`Expected numeric scalar ${p}`);if(S.format!=="float32"&&(!Number.isInteger(w)||w<(S.format==="uint32"?0:-2147483648)||w>(S.format==="uint32"?4294967295:2147483647)))throw new Error(`Scalar ${p} is outside its declared integer format`)}else if(v){if(!(w instanceof z))throw new Error(`Expected GPUVector ${p}`);sn(e,w,v.format,v.length,v.chunkLengths)}else throw new Error(`Undeclared binding ${p}`);s.set(p,w)}for(let p of this.operations){p instanceof Ne&&i.values.has(p.input)&&io(i.values.get(p.input),i.values.get(p.output));for(let E of this.contracts.get(p)?.values??[]){let O=k(E.value);E.access!=="write"&&s.get(O)instanceof z&&y.add(O)}if(!(p instanceof $e)){let E=this.contracts.get(p);for(let O of E?.values??[]){let C=k(O.value);if(O.access!=="write"&&!s.has(C)&&!i.values.has(C)&&!u.has(C)&&!g.has(C))throw new Error(`Missing ${O.access==="read-write"?"read-write":"execution"} binding ${C}`)}for(let O of E?.values??[]){let C=k(O.value);O.access!=="read"&&this.scalars.some(U=>U.id===C)&&g.add(C)}for(let O of E?.requiredFeatures??[])if(!e.features.has(O))throw new Error(`Operation requires ${O}`);for(let O of E?.values??[]){if(O.access==="read")continue;let C=this.vectors.find(qe=>qe.id===k(O.value));if(!C)continue;let U=s.get(C.id),M=h.get(C.id)??(U instanceof z?U:void 0),V=O.shape,de=V&&"like"in V?d(k(V.like)):void 0;if(V&&"like"in V&&!de)throw new Error(`Missing shape input ${k(V.like)}`);let te=de?de.chunkLengths:V&&"length"in V?V.chunkLengths??C.chunkLengths??[V.length]:C.chunkLengths??(C.length===void 0?void 0:[C.length]);if(O.access==="read-write"&&!(U instanceof z))throw new Error(`Missing read-write binding ${C.id}`);if(O.access==="read-write"&&M!==U)throw new Error(`Read-write target must use its bound storage: ${C.id}`);if(y.has(C.id)&&M!==U)throw new Error(`Output target replaces an earlier read: ${C.id}`);if(!M&&!te)throw new Error(`Cannot infer length of produced vector ${C.id}`);let He=te?.reduce((qe,ut)=>qe+ut,0)??M.length;if(C.length!==void 0&&C.length!==He||V&&"length"in V&&V.length!==He)throw new Error(`Length constraint failed for ${C.id}`);if(C.chunkLengths&&te&&(C.chunkLengths.length!==te.length||C.chunkLengths.some((qe,ut)=>qe!==te[ut])))throw new Error(`Chunk constraint failed for ${C.id}`);M?(sn(e,M,C.format,He,te),Po(C.id,M,s),s.set(C.id,M)):f(C.id,te,C.format)}continue}let w=this.expressions.find(E=>E.operation===p),S=[];for(let E of w.references){if(s.get(E)===void 0&&!u.has(E)&&!w.gpuScalarInputs.includes(E))throw new Error(`Missing execution binding ${E}`);let C=d(E);C&&this.vectors.some(U=>U.id===E)&&S.push(C)}let v=this.vectors.find(E=>E.id===w.operation.output),T=S[0],b=v?T?.chunkLengths??v.chunkLengths??(v.length===void 0?void 0:[v.length]):[1];if(!b)throw new Error(`Cannot infer length of ${w.operation.output}`);for(let E of S)if(E.chunkLengths.length!==b.length||E.chunkLengths.some((O,C)=>O!==b[C]))throw new Error(`Expression ${w.operation.id} requires matching vector chunk boundaries`);let P=b.reduce((E,O)=>E+O,0);if(v?.length!==void 0&&v.length!==P)throw new Error(`Length constraint failed for ${v.id}`);if(v?.chunkLengths&&(v.chunkLengths.length!==b.length||v.chunkLengths.some((E,O)=>E!==b[O])))throw new Error(`Chunk constraint failed for ${v.id}`);let B=h.get(w.operation.output);B?(sn(e,B,w.format,P,b),Po(w.operation.output,B,s),s.set(w.operation.output,B)):f(w.operation.output,b,w.format)}for(let p of Object.keys(n.outputTargets??{})){let w=this.outputs.includes(p)&&this.scalars.some(S=>S.id===p);if(!l.has(p)&&!m.has(p)&&!w&&!this.textures.some(S=>S.id===p&&S.role==="value"))throw new Error(`Unknown graph output target ${p}`)}for(let p of this.outputs)if(!(s.get(p)instanceof z)&&this.scalars.some(w=>w.id===p)){let w=h.get(p);if(w){sn(e,w,this.scalars.find(v=>v.id===p).format,1,[1]),Po(p,w,s),s.set(p,w);continue}let S=ms(e,p,[1],this.scalars.find(v=>v.id===p).format);a.add(S),s.set(p,S)}return new Co(this,s,a,u,i)}catch(p){i.destroy();for(let w of a)w.destroy();throw p}}};function ps(r,e){if(r instanceof H&&(r.type==="composite"||r instanceof st&&!r.predicate)){let t=new Set,n=new Set;for(let o of r.operations){let i=(ps(o,e)?.values??[]).filter(s=>e.some(a=>a.id===k(s.value)));for(let s of i){let a=k(s.value);s.access!=="write"&&!n.has(a)&&t.add(a)}for(let s of i)s.access!=="read"&&n.add(k(s.value))}return{values:[...new Set([...t,...n])].map(o=>({value:o,access:t.has(o)?n.has(o)?"read-write":"read":"write"}))}}return Pe(r)?r.contract:void 0}var Co=class{program;values;owned;transientVectors;textures;constructor(e,t,n,o=new Map,i){this.program=e,this.values=t,this.owned=n,this.transientVectors=o,this.textures=i}getOutputs(){let e=Object.create(null);for(let t of this.program.outputs){let n=this.textures?.values.get(t)??this.values.get(t);if(!(n instanceof z||n instanceof ye.Texture||n instanceof ye.TextureView))throw new Error(`Output ${t} has no materialized resource`);e[t]=n}return e}finish(){let e=this.getOutputs();for(let t of Object.values(e))t instanceof z&&this.owned.delete(t);return this.textures?.finish(this.program.outputs),this.destroy(),e}destroy(){this.textures?.destroy();for(let e of this.owned)e.destroy();this.owned.clear()}};function ms(r,e,t,n="float32"){let o=[];try{for(let i of t)o.push(new Gt({buffer:r.createBuffer({byteLength:Math.max(1,i)*J(n).components*4,usage:ye.Buffer.STORAGE|ye.Buffer.VERTEX|ye.Buffer.COPY_SRC|ye.Buffer.COPY_DST}),format:n,length:i,ownsBuffer:!0}));return new z({type:"data",name:e,format:n,data:o,ownsData:!0})}catch(i){for(let s of o)s.destroy();throw i}}function sn(r,e,t,n,o){if(e.format!==t||n!==void 0&&e.length!==n)throw new Error(`Incompatible vector ${e.name}`);if(o&&(o.length!==e.data.length||o.some((s,a)=>s!==e.data[a].length)))throw new Error(`Incompatible chunks for ${e.name}`);let i=I(e.format).byteLength;for(let s of e.data)if(s.buffer.device!==r||s.byteStride!==i||s.byteOffset%4!==0||s.rowByteLength!==i)throw new Error(`Expression vector ${e.name} must contain packed 32-bit numeric chunks on the execution device`)}function Po(r,e,t){let n=i=>i.buffer instanceof ye.Buffer?i.buffer:i.buffer.buffer,o=new Map;for(let i of e.data){if(i.length===0)continue;let s=n(i),a=o.get(s)??[];a.push({start:i.byteOffset,end:i.byteOffset+i.length*i.byteStride}),o.set(s,a)}for(let i of o.values())if(i.sort((s,a)=>s.start-a.start),i.some((s,a)=>a>0&&s.start<i[a-1].end))throw new Error(`Output ${r} has overlapping writable chunks`);for(let[i,s]of t)if(i!==r&&s instanceof z&&s.data.some(a=>o.has(n(a))))throw new Error("Expression output targets must not alias inputs or earlier outputs")}var bs=R(A(),1);var Nt={float32:"f32",sint32:"i32",uint32:"u32"};function gs(r,e,t,n){if(e===t)return r;let o=Nt;if(t==="float32")return`${o.float32}(${r})`;if(e==="float32"){let s=n==="nearest"?`expression_round_nearest(${r})`:r;return`expression_to_${t}(${s})`}let i=t==="uint32"?`max(${r}, 0)`:`min(${r}, 2147483647u)`;return`${o[t]}(${i})`}var ys=`
392
392
  fn expression_round_nearest(value: f32) -> f32 {
393
393
  let magnitude = abs(value);
394
394
  let integral = floor(magnitude);
@@ -404,15 +404,33 @@ fn expression_to_uint32(value: f32) -> u32 {
404
404
  if (value >= 4294967296.0) { return 4294967295u; }
405
405
  if (value <= 0.0) { return 0u; }
406
406
  return u32(value);
407
- }`;var vo=64,tn=class{program;plan;kernel;vectorNames;scalarNames;outputIsScalar;constructor(e,t,n){this.program=t,this.plan=n,this.vectorNames=n.references.filter(d=>t.vectors.some(l=>l.id===d)),this.scalarNames=n.references.filter(d=>t.scalars.some(l=>l.id===d)),this.outputIsScalar=t.scalars.some(d=>d.id===n.operation.output);let i=this.scalarNames.length>0||this.outputIsScalar,o=d=>`metadata[${Math.floor(d/4)}][${d%4}]`,s=(d,l)=>{switch(Z(de(d,n.formats)).components===1&&(l=0),d.kind){case"literal":return`f32(${Object.is(d.value,-0)?"-0.0":d.value.toExponential()})`;case"swizzle":return s(d.argument,d.components[l]);case"construct":{let h=d.arguments.flatMap(p=>Array.from({length:Z(de(p,n.formats)).components},(y,g)=>({argument:p,component:g}))),m=h[h.length===1?0:l];return s(m.argument,m.component)}case"negate":return`(-${s(d.argument,l)})`;case"cast":return as(s(d.argument,l),Z(de(d.argument,n.formats)).componentType,d.format,n.operation.integerRounding);case"call":{let[h,m,p]=d.arguments;if(d.name==="select"){let y=Z(de(h,n.formats)).componentType;return`select(${s(p,l)}, ${s(m,l)}, ${s(h,l)} != ${Rt[y]}(0))`}if(["dot","length","equalAll"].includes(d.name)){let y=Z(de(h,n.formats)).components,g=Array.from({length:y},(S,v)=>{let T=s(h,v),b=s(d.name==="length"?h:m,v);return`(${T} ${d.name==="equalAll"?"==":"*"} ${b})`});if(d.name==="equalAll")return`select(0u, 1u, ${g.join(" && ")})`;let w=g.reduce((S,v)=>`(${S} + ${v})`,"0.0");return d.name==="length"?`sqrt(${w})`:w}return`${d.name}(${d.arguments.map(y=>s(y,l)).join(", ")})`}case"binary":return`(${s(d.left,l)} ${d.operator} ${s(d.right,l)})`;case"reference":{let h=this.vectorNames.indexOf(d.name),{components:m,componentType:p}=Z(n.formats.get(d.name));return h>=0?`input${h}[${o(h+2)} + index * ${m}u + ${m===1?0:l}u]`:`bitcast<${Rt[p]}>(gpuValues[${t.scalars.findIndex(y=>y.id===d.name)}])`}}},a=this.vectorNames.map((d,l)=>({name:`input${l}`,type:"read-only-storage",group:0,location:l})),u=[...a],c=a.map((d,l)=>`@group(0) @binding(${d.location}) var<storage, read> ${d.name}: array<${Rt[Z(n.formats.get(this.vectorNames[l])).componentType]}>;`);this.outputIsScalar||(c.push(`@group(0) @binding(${u.length}) var<storage, read_write> outputValues: array<${Rt[Z(n.format).componentType]}>;`),u.push({name:"outputValues",type:"storage",group:0,location:u.length})),i&&(c.push(`@group(0) @binding(${u.length}) var<storage, ${this.outputIsScalar?"read_write":"read"}> gpuValues: array<u32>;`),u.push({name:"gpuValues",type:this.outputIsScalar?"storage":"read-only-storage",group:0,location:u.length})),c.push(`@group(0) @binding(${u.length}) var<uniform> metadata: array<vec4u, ${Math.ceil((this.vectorNames.length+2)/4)}>;`),u.push({name:"metadata",type:"uniform",group:0,location:u.length});let f=this.outputIsScalar?`gpuValues[${t.scalars.findIndex(d=>d.id===n.operation.output)}] = bitcast<u32>(${s(n.expression,0)});`:Array.from({length:Z(n.format).components},(d,l)=>`outputValues[${o(1)} + index * ${Z(n.format).components}u + ${l}u] = ${s(n.expression,l)};`).join(`
408
- `);this.kernel=new _(e,{id:n.operation.id,source:`${c.join(`
407
+ }`;var Lo=64,an=class{program;plan;kernel;vectorNames;scalarNames;outputIsScalar;constructor(e,t,n){this.program=t,this.plan=n,this.vectorNames=n.references.filter(f=>t.vectors.some(l=>l.id===f)),this.scalarNames=n.references.filter(f=>t.scalars.some(l=>l.id===f)),this.outputIsScalar=t.scalars.some(f=>f.id===n.operation.output);let o=this.scalarNames.length>0||this.outputIsScalar,i=f=>`metadata[${Math.floor(f/4)}][${f%4}]`,s=(f,l)=>{switch(J(fe(f,n.formats)).components===1&&(l=0),f.kind){case"literal":return`f32(${Object.is(f.value,-0)?"-0.0":f.value.toExponential()})`;case"swizzle":return s(f.argument,f.components[l]);case"construct":{let h=f.arguments.flatMap(g=>Array.from({length:J(fe(g,n.formats)).components},(y,p)=>({argument:g,component:p}))),m=h[h.length===1?0:l];return s(m.argument,m.component)}case"negate":return`(-${s(f.argument,l)})`;case"cast":return gs(s(f.argument,l),J(fe(f.argument,n.formats)).componentType,f.format,n.operation.integerRounding);case"call":{let[h,m,g]=f.arguments;if(f.name==="select"){let y=J(fe(h,n.formats)).componentType;return`select(${s(g,l)}, ${s(m,l)}, ${s(h,l)} != ${Nt[y]}(0))`}if(["dot","length","equalAll"].includes(f.name)){let y=J(fe(h,n.formats)).components,p=Array.from({length:y},(S,v)=>{let T=s(h,v),b=s(f.name==="length"?h:m,v);return`(${T} ${f.name==="equalAll"?"==":"*"} ${b})`});if(f.name==="equalAll")return`select(0u, 1u, ${p.join(" && ")})`;let w=p.reduce((S,v)=>`(${S} + ${v})`,"0.0");return f.name==="length"?`sqrt(${w})`:w}return`${f.name}(${f.arguments.map(y=>s(y,l)).join(", ")})`}case"binary":return`(${s(f.left,l)} ${f.operator} ${s(f.right,l)})`;case"reference":{let h=this.vectorNames.indexOf(f.name),{components:m,componentType:g}=J(n.formats.get(f.name));return h>=0?`input${h}[${i(h+2)} + index * ${m}u + ${m===1?0:l}u]`:`bitcast<${Nt[g]}>(gpuValues[${t.scalars.findIndex(y=>y.id===f.name)}])`}}},a=this.vectorNames.map((f,l)=>({name:`input${l}`,type:"read-only-storage",group:0,location:l})),u=[...a],c=a.map((f,l)=>`@group(0) @binding(${f.location}) var<storage, read> ${f.name}: array<${Nt[J(n.formats.get(this.vectorNames[l])).componentType]}>;`);this.outputIsScalar||(c.push(`@group(0) @binding(${u.length}) var<storage, read_write> outputValues: array<${Nt[J(n.format).componentType]}>;`),u.push({name:"outputValues",type:"storage",group:0,location:u.length})),o&&(c.push(`@group(0) @binding(${u.length}) var<storage, ${this.outputIsScalar?"read_write":"read"}> gpuValues: array<u32>;`),u.push({name:"gpuValues",type:this.outputIsScalar?"storage":"read-only-storage",group:0,location:u.length})),c.push(`@group(0) @binding(${u.length}) var<uniform> metadata: array<vec4u, ${Math.ceil((this.vectorNames.length+2)/4)}>;`),u.push({name:"metadata",type:"uniform",group:0,location:u.length});let d=this.outputIsScalar?`gpuValues[${t.scalars.findIndex(f=>f.id===n.operation.output)}] = bitcast<u32>(${s(n.expression,0)});`:Array.from({length:J(n.format).components},(f,l)=>`outputValues[${i(1)} + index * ${J(n.format).components}u + ${l}u] = ${s(n.expression,l)};`).join(`
408
+ `);this.kernel=new F(e,{id:n.operation.id,source:`${c.join(`
409
409
  `)}
410
- ${us}
411
- @compute @workgroup_size(${vo})
410
+ ${ys}
411
+ @compute @workgroup_size(${Lo})
412
412
  fn main(@builtin(workgroup_id) workgroup: vec3u, @builtin(num_workgroups) dimensions: vec3u, @builtin(local_invocation_index) localIndex: u32) {
413
- let index = (workgroup.y * dimensions.x + workgroup.x) * ${vo}u + localIndex;
414
- if (index >= ${o(0)}) { return; }
415
- ${f}
416
- }`,shaderLayout:{bindings:u}})}lower(e){let t=this.vectorNames.map(u=>e.resolveVector(this.program.vectors.find(c=>c.id===u))),n=this.outputIsScalar?e.resolveScalar(this.program.scalars.find(u=>u.id===this.plan.operation.output)):void 0,i=this.outputIsScalar?void 0:e.resolveVector(this.program.vectors.find(u=>u.id===this.plan.operation.output)),o=n?.arena??(this.scalarNames.length?e.resolveScalar(this.program.scalars.find(u=>u.id===this.scalarNames[0])).arena:void 0),a=(i?.data??[n.view]).flatMap((u,c)=>{if(u.length===0)return[];let f=t.map(y=>y.data[c]);if(f.some(y=>!y||y.length!==u.length))throw new Error("Expression chunk mismatch");let d=Math.ceil(u.length/vo),l=e.graph.device.limits.maxComputeWorkgroupsPerDimension,h=Math.min(d,l),m=Math.ceil(d/h);if(m>l)throw new Error("Expression chunk exceeds dispatch limits");let p=[...f.map(y=>({buffer:y,usage:"storage-read"})),...i?[{buffer:u,usage:"storage-write"}]:[],...o?[{buffer:o.buffer,usage:this.outputIsScalar?"storage-read-write":"storage-read"}]:[]];return[z(N({id:`${this.plan.operation.id}-chunk-${c}`,resources:p,compile:({device:y})=>{let g=new Uint32Array(Math.ceil((this.vectorNames.length+2)/4)*4);g.set([u.length,L(u),...f.map(L)]);let w=y.createBuffer({data:g,usage:cs.Buffer.UNIFORM});return{encode:({computePass:S,getBuffer:v})=>{let T={metadata:w};f.forEach((b,P)=>{T[`input${P}`]=$(b,v)}),i&&(T.outputValues=$(u,v)),o&&(T.gpuValues=v(o.buffer)),this.kernel.dispatch(S,{bindings:T,x:h,y:m,z:1})},destroy:()=>w.destroy()}}}),[h,m,1])]});Re(e.graph,a),e.recordDecision({operationId:this.plan.operation.id,operationType:"expression",lowering:"webgpu-expression",reason:"shape-independent expression shader with execution-time chunk dimensions"})}destroy(){this.kernel.destroy()}};var ye=class{type="cpu";id;inputs;outputs;execute;constructor(e){this.id=e.id,this.inputs=Object.freeze({...e.inputs}),this.outputs=Object.freeze(Object.fromEntries(Object.entries(e.outputs).map(([t,n])=>[t,Object.freeze({...n,...n.chunkLengths?{chunkLengths:Object.freeze([...n.chunkLengths])}:{}})]))),this.execute=e.execute}get contract(){return{outputs:this.outputs,values:[...Object.values(this.inputs).map(e=>({value:e,access:"read"})),...Object.keys(this.outputs).map(e=>({value:e,access:"write"}))]}}};var J=V(R(),1);var fr=class{device;program;compileStage;stages=[];constructor(e,t,n){this.device=e,this.program=t,this.compileStage=n,(0,J.assert)(!t.textures.length&&!t.vectors.some(s=>s.role==="state"));let i=[...t.scalars,...t.vectors],o=(s,a)=>{let u=i.find(f=>f.id===a);(0,J.assert)(u);let c=t.vectors.find(f=>f.id===a);c?s.addInput(a,W.vector(c.format,{length:c.length,chunkLengths:c.chunkLengths})):s.addInput(a,W.scalar(t.scalars.find(f=>f.id===a).format))};try{for(let s of t.operations){if(s instanceof ye){this.stages.push(s);continue}(0,J.assert)("contract"in s&&s.contract);let a=s.contract.values.filter(f=>f.access!=="write").map(f=>typeof f.value=="string"?f.value:f.value.id),u=s.contract.values.filter(f=>f.access!=="read").map(f=>typeof f.value=="string"?f.value:f.value.id),c=new Pe;for(let f of new Set(a))o(c,f);for(let f of new Set(u)){let d=t.vectors.find(l=>l.id===f);d&&c.addDeclaration(f,W.vector(d.format,{length:d.length,chunkLengths:d.chunkLengths}),"value")}c.add(s),this.stages.push({graph:n(c,u),inputs:a})}}catch(s){throw this.destroy(),s}}async run(e,t={}){for(let[u,c]of Object.entries(t))(0,J.assert)(this.program.outputs.includes(u)&&(c==="cpu"||c==="gpu"));let n=new Map;for(let u of[...this.program.vectors,...this.program.scalars].filter(c=>c.role==="input")){let c=e[u.id];if((0,J.assert)(c!==void 0),!(c instanceof we)){let f=new Pe,d=this.program.vectors.find(l=>l.id===u.id);d?f.addInput(u.id,W.vector(d.format,{length:d.length,chunkLengths:d.chunkLengths})):f.addInput(u.id,W.scalar(this.program.scalars.find(l=>l.id===u.id).format)),new Ft(f,{outputs:[]}).prepare(this.device,{[u.id]:c}).finish()}if(c instanceof we){(0,J.assert)(c.data.every(d=>!d.nullBitmap&&!d.valueOffsets)),(0,J.assert)(c.format===u.format);let f=this.program.vectors.find(d=>d.id===u.id);(0,J.assert)(f&&(f.length===void 0||f.length===c.length)),(0,J.assert)(!f.chunkLengths||f.chunkLengths.length===c.data.length&&f.chunkLengths.every((d,l)=>d===c.data[l].length)),n.set(u.id,c)}}let i={...e},o=new Set,s=async u=>{let c=n.get(u);if(!c){let f=i[u];(0,J.assert)(f instanceof j);let d=await $u(f);c=ds(d.format,d.chunks.map(l=>l.values)),n.set(u,c)}return ku(c)},a=async u=>{let c=i[u];if(c instanceof j)return c;let f=await s(u),d=new Pe;d.add(new Me({output:u,format:f.format,data:f.chunks.map(h=>h.values)}));let l=this.compileStage(d);try{let h=(await l.run({}))[u];return o.add(h),i[u]=h,h}finally{l.destroy()}};try{for(let c of this.stages){let f;if(c instanceof ye){let d=Object.create(null);for(let[h,m]of Object.entries(c.inputs)){let p=i[m],y=typeof p=="number"?p:await s(m);d[h]=typeof y!="number"&&this.program.scalars.some(g=>g.id===m)?y.pack()[0]:y}let l=await c.execute({inputs:d});(0,J.assert)(Object.keys(l).length===Object.keys(c.outputs).length);for(let h of Object.keys(c.outputs)){let m=this.program.vectors.find(S=>S.id===h),p=l[h];(0,J.assert)(p);let y="chunks"in p?p.chunks.map(S=>S.values):[p],g=new Me({output:h,format:m.format,data:y}),w=g.chunkLengths.reduce((S,v)=>S+v,0);(0,J.assert)(m.length===void 0||m.length===w),(0,J.assert)(!m.chunkLengths||m.chunkLengths.length===y.length&&m.chunkLengths.every((S,v)=>S===g.chunkLengths[v])),n.set(h,ds(m.format,y)),delete i[h]}continue}else{let d=Object.create(null);for(let l of c.inputs){let h=i[l];d[l]=this.program.scalars.some(m=>m.id===l)?typeof h=="number"?h:(await s(l)).pack()[0]:await a(l)}f=await c.graph.run({inputs:d})}for(let[d,l]of Object.entries(f))n.delete(d),i[d]=l,o.add(l)}let u=Object.create(null);for(let c of this.program.outputs)t[c]==="cpu"?(await s(c),u[c]=n.get(c)):u[c]=await a(c);for(let c of Object.values(u))c instanceof j&&o.delete(c);return u}finally{for(let u of o)u.destroy()}}destroy(){for(let e of this.stages)e instanceof ye||e.graph.destroy()}};async function $u(r){(0,J.assert)(r.format);let e=U(r.format),t=e.signedDataType==="float32"?Float32Array:e.signedDataType==="uint32"?Uint32Array:Int32Array,n=[];for(let i of r.data){let o=new t(i.length*e.byteLength/4);if(i.length){let s=await i.buffer.readAsync(i.byteOffset,(i.length-1)*i.byteStride+e.byteLength),a=new Uint8Array(o.buffer);for(let u=0;u<i.length;u++)a.set(s.subarray(u*i.byteStride,u*i.byteStride+e.byteLength),u*e.byteLength)}n.push({values:o,length:i.length})}return{format:r.format,length:r.length,chunks:n,pack(){let i=new t(n.reduce((s,a)=>s+a.values.length,0)),o=0;for(let s of n)i.set(s.values,o),o+=s.values.length;return i}}}function ds(r,e){let t=U(r).byteLength;return new we({format:r,data:e.map(n=>new Jt({buffer:n,format:r,length:n.byteLength/t}))})}function ku(r){let e=r.format;(0,J.assert)(/^(float32|sint32|uint32)(x[234])?$/.test(e));let t=U(e),n=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array,i=r.data.map(o=>{let s=new n(o.length*t.components),a=new Uint8Array(s.buffer);for(let u=0;u<o.length;u++)a.set(new Uint8Array(o.buffer,o.byteOffset+u*o.byteStride,t.byteLength),u*t.byteLength);return{values:s,length:o.length}});return{format:e,length:r.length,chunks:i,pack(){let o=new n(r.length*t.components),s=0;for(let a of i)o.set(a.values,s),s+=a.values.length;return o}}}var Mt=class r{device;program;stageLowerings;compiler;kernels=new Map;destroyed=!1;runningCPU=!1;cpuExecution;outputLocations;constructor(e,t,n={},i){if(this.device=e,e.type!=="webgpu")throw new Error("GPUGraph execution requires WebGPU");if(this.program=new Ft(t,n),this.outputLocations=n.outputLocations??{},this.stageLowerings=i??n.lowerings??[],this.compiler=new xt(e,[...i??n.lowerings??[],{type:"expression",lower:(o,s)=>this.kernels.get(o).lower(s)}]),this.program.operations.some(o=>o instanceof ye)||Object.values(this.outputLocations).includes("cpu")){this.cpuExecution=new fr(e,this.program,(o,s)=>new r(e,o,{outputs:s},i??n.lowerings));return}try{for(let o of this.program.expressions)this.kernels.set(o.operation,new tn(e,this.program,o))}catch(o){throw this.destroy(),o}}async run(e,t={}){(0,wt.assert)(!this.destroyed&&!this.runningCPU);let n="inputs"in e?e.inputs:e,i=this.program.operations.some(a=>a instanceof ye)||Object.values(this.outputLocations).includes("cpu")||Object.values(n??{}).some(a=>a instanceof we);if(!this.cpuExecution&&i&&(this.cpuExecution=new fr(this.device,this.program,(a,u)=>new r(this.device,a,{outputs:u},this.stageLowerings))),i&&this.cpuExecution){let a=this.program.resolveBindings(e,t);(0,wt.assert)(!a.options.outputTargets||Object.keys(a.options.outputTargets).length===0),this.runningCPU=!0;try{return await this.cpuExecution.run(a.bindings,this.outputLocations)}finally{this.runningCPU=!1}}let o=this.prepare(e,t),s;try{return s=this.device.createCommandEncoder(),o.encode(s),this.device.submit(s.finish()),o.outputs}catch(a){throw o.discard(),a}finally{o.destroy(),s?.destroy()}}prepare(e,t={}){if((0,wt.assert)(!this.destroyed),this.program.operations.some(a=>a instanceof ye)||Object.values(this.outputLocations).includes("cpu"))throw new Error("CPU operations require asynchronous run(), not prepare()");let n=this.program.resolveBindings(e,t),i=n.bindings;t=n.options;let o=this.program.prepare(this.device,i,t,!0),s;try{let a=new Pe;for(let l of this.program.scalars)a.scalar(l.id,l.format);let u=Object.create(null),c=Object.create(null);for(let[l,h]of o.values)typeof h=="number"?c[l]=h:this.program.vectors.some(m=>m.id===l)&&(u[l]=h);for(let[l,h]of Object.entries(i))typeof h=="number"&&(c[l]=h);for(let l of this.program.vectors){let h=u[l.id],m=o.transientVectors.get(l.id);if(m){a.addDeclaration(l.id,{type:"vector",format:l.format,length:m.length,chunkLengths:m.chunkLengths},"value");continue}if(!h&&l.length===void 0)throw new Error(`Missing length or execution binding for ${l.id}`);a.vector(l.id,l.format,h?.length??l.length,{external:!!h,chunkLengths:h?.data.map(p=>p.length)??l.chunkLengths})}let f=Object.create(null);for(let l of this.program.textures){let h=o.textures.values.get(l.id),m=ae(h);a.texture(l.id,{format:m.format,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples,usage:m.texture.props.usage,external:!0}),f[l.id]=h}a.add(this.program.operations);let d=this.compiler.compile(a,{vectors:u,scalars:c,textures:f});for(let l of this.program.scalars){let h=o.values.get(l.id);if(!(h instanceof j))continue;let m=d.scalars.get(l.id).view,p=d.graph.importGPUVector(`${l.id}-result`,h).data[0];d.graph.addCopyPass({id:`${l.id}-result-copy`,resources:[{buffer:m,usage:"copy-source"},{buffer:p,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:y,getBuffer:g})=>y.copyBufferToBuffer({sourceBuffer:g(m),sourceOffset:m.byteOffset,destinationBuffer:g(p),destinationOffset:p.byteOffset,size:4})})})}return s=d.graph.compile(),new lr(this.device,o,s,()=>{(0,wt.assert)(!this.destroyed)})}catch(a){throw s?.destroy(),o.destroy(),a}}destroy(){(0,wt.assert)(!this.runningCPU),this.cpuExecution?.destroy();for(let e of this.kernels.values())e.destroy();this.kernels.clear(),this.destroyed=!0}},lr=class{device;invocation;executable;checkProgram;outputs;encoded=!1;destroyed=!1;constructor(e,t,n,i){this.device=e,this.invocation=t,this.executable=n,this.checkProgram=i,this.outputs=t.getOutputs()}encode(e){(0,wt.assert)(!this.destroyed&&!this.encoded&&e.device===this.device),this.checkProgram(),this.encoded=!0,this.executable.encode(e,{parameters:void 0})}destroy(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.finish())}discard(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.destroy())}};var Pe=class r{id;programOperations=[];programScalars=new Map;programVectors=new Map;programTextures=new Map;constructor(e={}){this.id=e.id??"gpu-program"}add(e){return this.assertOperationLike(e),this.addOperationLike(e),this}addInput(e,t){return this.addDeclaration(e,t,"input")}addState(e,t){if(t.type!=="vector")throw new Error("Graph state requires vector storage");return this.addDeclaration(e,t,"state")}addDeclaration(e,t,n){if(this.assertValueId(e),t.type==="texture"){let o=new ie({id:e,...t,usage:0,role:n,descriptor:t,external:n==="input",..."width"in(t.extent??{})?t.extent:{}});return this.programTextures.set(e,o),o}if(t.type==="scalar"){let o=new Oe(e,t.format,n);return this.programScalars.set(e,o),o}let i=new K({id:e,...t,role:n,external:n==="input"||n==="state"});return this.programVectors.set(e,i),i}scalar(e,t){this.assertValueId(e);let n=new Oe(e,t);return this.programScalars.set(e,n),n}vector(e,t,n,i={}){this.assertValueId(e);let o=typeof n=="number"?{length:n,...i}:n??i,s=new K({id:e,format:t,...o});return this.programVectors.set(e,s),s}texture(e,t){this.assertValueId(e);let n=new ie({...t,id:e});return this.programTextures.set(e,n),n}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new Ue(e,t)}compile(e,t={}){return new Mt(e,this,t)}constrainResult(e,t){if(e.length!==void 0&&t.length!==void 0&&e.length!==t.length)throw new Error(`Incompatible result length ${e.id}`);if(e.chunkLengths&&t.chunkLengths&&(e.chunkLengths.length!==t.chunkLengths.length||e.chunkLengths.some((i,o)=>i!==t.chunkLengths[o])))throw new Error(`Incompatible result chunks ${e.id}`);let n=new K({...e,length:e.length??t.length,chunkLengths:e.chunkLengths??t.chunkLengths});return this.programVectors.set(e.id,n),n}clone(){let e=new r({id:this.id});for(let[t,n]of this.programScalars)e.programScalars.set(t,n);for(let[t,n]of this.programVectors)e.programVectors.set(t,n);for(let[t,n]of this.programTextures)e.programTextures.set(t,n);return e.programOperations.push(...this.programOperations),e}get textures(){return Object.freeze([...this.programTextures.values()])}get scalars(){return Object.freeze([...this.programScalars.values()])}get vectors(){return Object.freeze([...this.programVectors.values()])}get operations(){return Object.freeze([...this.programOperations])}get operationTree(){return Object.freeze(this.programOperations.map(yo))}assertValueId(e){if(this.programScalars.has(e)||this.programVectors.has(e)||this.programTextures.has(e))throw new Error(`${this.id} value "${e}" already exists`)}addOperationLike(e){if(Array.isArray(e)){for(let t of e)this.addOperationLike(t);return}this.programOperations.push(e)}assertOperationLike(e){if(Array.isArray(e)){for(let t of e)this.assertOperationLike(t);return}if(!e||typeof e!="object")throw new Error(`${this.id} accepts GPU operations only`)}};function So(r,e={}){return new q({id:e.id,operations:r})}function Eo(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:fs(r.program.operationTree),loweredNodeCount:r.lowering.nodes.length,loweringDecisionCount:r.lowering.decisions.length,scalarCount:r.program.scalars.length,vectorCount:r.program.vectors.length,externalVectorCount:r.program.vectors.filter(t=>t.external).length,cpuReadbackCount:0,backend:"webgpu",decisions:Object.freeze(e)})}function fs(r){return r.reduce((e,t)=>e+1+fs(t.children??[]),0)}var nn=class{adapter;minimumSampleCount;explorationEnabled;calibrations=new Map;constructor(e){if(!Number.isSafeInteger(e.minimumSampleCount??1)||(e.minimumSampleCount??1)<=0)throw new Error("GPUCommandGraph autotuner minimumSampleCount must be a positive safe integer");if(this.adapter=Au(e.adapter),this.minimumSampleCount=e.minimumSampleCount??1,this.explorationEnabled=e.explorationEnabled??!0,e.profile?.adapter.key===this.adapter.key&&e.profile.version===1)for(let t of e.profile.calibrations)this.importCalibration(t)}selectKernel(e){rn(e.operation,"operation"),ms(e.workloadSize);let t=e.candidates.filter(a=>a.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let a of t)rn(a.id,"variant");let n=hs(e.workloadSize),i=t.map(a=>{let u=this.findNearestCalibration(e.operation,a.id,n);return{candidate:a,calibration:u,sampleCount:u?.workloadBucket===n?u.sampleCount:0,estimatedDurationMilliseconds:u?_u(u,e.workloadSize):void 0}});if(this.explorationEnabled){let a=i.find(u=>u.sampleCount<this.minimumSampleCount);if(a)return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:"exploration",sampleCount:a.sampleCount,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}let o=i.filter(a=>a.estimatedDurationMilliseconds!==void 0).sort((a,u)=>(a.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],s=o??i[0];return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:o?"calibrated":"fallback",sampleCount:s.calibration?.sampleCount??0,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}observeKernel(e){if(rn(e.operation,"operation"),rn(e.variant,"variant"),ms(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=hs(e.workloadSize),n=Po(e.operation,e.variant,t),i=this.calibrations.get(n)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};i.sampleCount++,i.meanWorkloadSize+=(e.workloadSize-i.meanWorkloadSize)/i.sampleCount;let o=e.durationMilliseconds-i.meanDurationMilliseconds;return i.meanDurationMilliseconds+=o/i.sampleCount,i.durationSquaredDifferenceSum+=o*(e.durationMilliseconds-i.meanDurationMilliseconds),this.calibrations.set(n,i),ls(i)}observeTimingReport(e,t){let n=new Map(t.nodes.map(o=>[o.id,o])),i=0;for(let o of e.nodes){let s=n.get(o.id);o.gpuTimeMilliseconds===void 0||!s?.operation||!s.variant||(this.observeKernel({operation:s.operation,variant:s.variant,workloadSize:Math.max(s.maximumInvocationCount,1),durationMilliseconds:o.gpuTimeMilliseconds}),i++)}return i}exportProfile(){let e=[...this.calibrations.values()].sort((t,n)=>t.operation.localeCompare(n.operation)||t.variant.localeCompare(n.variant)||t.workloadBucket-n.workloadBucket).map(ls);return Object.freeze({version:1,adapter:this.adapter,calibrations:Object.freeze(e)})}reset(){this.calibrations.clear()}importCalibration(e){!e.operation||!e.variant||!Number.isSafeInteger(e.workloadBucket)||!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0||!Number.isFinite(e.meanWorkloadSize)||e.meanWorkloadSize<=0||!Number.isFinite(e.meanDurationMilliseconds)||e.meanDurationMilliseconds<0||this.calibrations.set(Po(e.operation,e.variant,e.workloadBucket),{operation:e.operation,variant:e.variant,workloadBucket:e.workloadBucket,sampleCount:e.sampleCount,meanWorkloadSize:e.meanWorkloadSize,meanDurationMilliseconds:e.meanDurationMilliseconds,durationSquaredDifferenceSum:e.sampleCount>1?e.durationStandardDeviationMilliseconds**2*(e.sampleCount-1):0})}findNearestCalibration(e,t,n){let i=this.calibrations.get(Po(e,t,n));if(i)return i;let o;for(let s of this.calibrations.values())s.operation!==e||s.variant!==t||(!o||Math.abs(s.workloadBucket-n)<Math.abs(o.workloadBucket-n))&&(o=s);return o}};function ps(r){let e=[...r.features].sort(),t={type:r.info.type,vendor:r.info.vendor,renderer:r.info.renderer,version:r.info.version,gpu:r.info.gpu,gpuType:r.info.gpuType,...r.info.gpuArchitecture?{gpuArchitecture:r.info.gpuArchitecture}:{},...r.info.gpuBackend?{gpuBackend:r.info.gpuBackend}:{},...r.info.featureLevel?{featureLevel:r.info.featureLevel}:{},features:Object.freeze(e),...r.info.subgroupMinSize===void 0?{}:{subgroupMinSize:r.info.subgroupMinSize},...r.info.subgroupMaxSize===void 0?{}:{subgroupMaxSize:r.info.subgroupMaxSize},maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension};return Object.freeze({key:JSON.stringify(t),...t})}function Au(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function ls(r){return Object.freeze({operation:r.operation,variant:r.variant,workloadBucket:r.workloadBucket,sampleCount:r.sampleCount,meanWorkloadSize:r.meanWorkloadSize,meanDurationMilliseconds:r.meanDurationMilliseconds,durationStandardDeviationMilliseconds:r.sampleCount>1?Math.sqrt(r.durationSquaredDifferenceSum/(r.sampleCount-1)):0})}function _u(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function hs(r){return Math.floor(Math.log2(Math.max(r,1)))}function Po(r,e,t){return`${r}\0${e}\0${t}`}function rn(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function ms(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var Fu={interactive:4,normal:8,background:16},on=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){gs(e.initialBudget);let t=e.latencyPriority??"normal",n=e.targetStepMilliseconds??Fu[t];mr(n,"targetStepMilliseconds");let i=e.minimumScale??.125,o=e.maximumScale??4,s=e.responsiveness??.25,a=e.maximumAdjustmentFactor??2;if(mr(i,"minimumScale"),mr(o,"maximumScale"),mr(a,"maximumAdjustmentFactor"),i>1||o<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(s)||s<=0||s>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(a<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=bs(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=n,this.minimumScale=i,this.maximumScale=o,this.responsiveness=s,this.maximumAdjustmentFactor=a}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,n=this.currentBudget){mr(t,"durationMilliseconds"),gs(n);let i=Ru(e,n);if(i>0){let o=this.targetStepMilliseconds*Math.min(i,1)/t,a=1+(ys(o,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=ys(this.currentScale*a,this.minimumScale,this.maximumScale),this.currentBudget=Mu(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:i,scale:this.currentScale,budget:this.currentBudget})}};function Ru(r,e){let t=[r.maximumInvocationCount/e.maximumInvocationCount];return e.maximumNodeCount!==void 0&&t.push(r.nodeCount/e.maximumNodeCount),e.maximumCommandCount!==void 0&&t.push(r.commandCount/e.maximumCommandCount),e.maximumReadByteLength!==void 0&&t.push(r.readByteLength/e.maximumReadByteLength),e.maximumWriteByteLength!==void 0&&t.push(r.writeByteLength/e.maximumWriteByteLength),Math.max(...t)}function Mu(r,e){return bs({maximumInvocationCount:hr(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:hr(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:hr(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:hr(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:hr(r.maximumWriteByteLength,e)}})}function hr(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function bs(r){return Object.freeze({...r})}function mr(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function gs(r){for(let[e,t]of[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Error(`GPUCommandGraph budget ${e} must be a positive safe integer`)}function ys(r,e,t){return Math.max(e,Math.min(t,r))}var an=class{maxSamples;getNodeGroup;graphs=new Map;encodingGraphs=new WeakMap;constructor(e={}){let t=e.maxSamples??120;if(!Number.isSafeInteger(t)||t<=0)throw new Error("GPUCommandGraphInspector maxSamples must be a positive safe integer");this.maxSamples=t,this.getNodeGroup=e.getNodeGroup}registerGraph(e){this.graphs.set(e.id,{id:e.id,stats:Vu(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:Nu(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let n of e.preflight?.nodes??[])this.getNode(t,n)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),n=new WeakMap,i=!0,o=()=>i&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(s,a)=>{let u=e.encode(s,a);return o()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async s=>{let a=n.get(s);if(a)return await a;if(o()&&this.encodingGraphs.get(s)===t){let u=this.recordGraphGPUTimings(e.id,t,s);return n.set(s,u),await u}},recordCounters:s=>{o()&&this.recordGraphCounters(t,s)},detach:()=>{i&&(i=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let n=this.getGraph(e);this.recordGraphEncoding(n,t)}async readResource(e,t,n){let i=this.getGraph(e);if(!i.encoding?.readResource)throw new Error("No live resource readback is available.");let o=await i.encoding.readResource(t,n);if(this.graphs.get(e)!==i)throw new Error("Graph registration changed during readback.");return o}recordCounters(e,t){this.recordGraphCounters(this.getGraph(e),t)}recordGraphEncoding(e,t){e.encoding=t,this.encodingGraphs.set(t,e);let{stats:n}=t;e.encodingCount++,this.addSample(e.cpuSamples,n.cpuEncodeTimeMilliseconds);for(let i of n.nodes){let o=this.getNode(e,i);this.addSample(o.cpuSamples,i.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let n=Object.entries(t);for(let[i,o]of n)if(!i||!Number.isFinite(o)||o<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[i,o]of n){let s=e.counters.get(i);s||(s=[],e.counters.set(i,s)),this.addSample(s,o)}}async recordGPUTimings(e,t){let i=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,i,t)}async recordGraphGPUTimings(e,t,n){if(this.graphs.get(e)!==t)return;let i;try{i=await n.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){i.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,i.gpuTimeMilliseconds);for(let o of i.nodes)if(o.gpuTimeMilliseconds!==void 0){let s=this.getNode(t,o);this.addSample(s.gpuSamples,o.gpuTimeMilliseconds)}return i}}getSnapshot(){let e=Array.from(this.graphs.values(),t=>this.getGraphSnapshot(t));return Object.freeze({graphs:Object.freeze(e)})}getGraph(e){let t=this.graphs.get(e);if(!t)throw new Error(`GPUCommandGraphInspector graph "${e}" is not registered`);return t}getNode(e,t){let n=e.nodes.get(t.id);if(n)return t.description!==void 0&&(n.description=t.description),t.resources!==void 0&&(n.resources=Co(t.resources)),n;let i=Co(t.resources),o=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:i}),s={id:t.id,resources:i,...t.description===void 0?{}:{description:t.description},type:t.type,...o===void 0?{}:{group:o},cpuSamples:[],gpuSamples:[]};return e.nodes.set(s.id,s),s}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],n=new Set;for(let s of e.stats.nodeOrder){let a=e.nodes.get(s);a&&(t.push(a),n.add(s))}for(let s of e.nodes.values())n.has(s.id)||t.push(s);let i=t.map(s=>Object.freeze({id:s.id,resources:s.resources,...s.description===void 0?{}:{description:s.description},type:s.type,...s.group===void 0?{}:{group:s.group},cpu:sn(s.cpuSamples),gpu:sn(s.gpuSamples)})),o=Array.from(e.counters,([s,a])=>zu(s,a));return Object.freeze({id:e.id,stats:e.stats,capabilities:e.capabilities,...e.preflight?{preflight:e.preflight}:{},encodingCount:e.encodingCount,timingReadFailureCount:e.timingReadFailureCount,totals:Object.freeze({cpu:sn(e.cpuSamples),gpu:sn(e.gpuSamples)}),counters:Object.freeze(o),nodes:Object.freeze(i)})}};function Vu(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function Nu(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:Co(e.resources)})))})}function sn(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,n)=>t-n);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:un(e,.5),p95Milliseconds:un(e,.95)})}function zu(r,e){let t=[...e].sort((n,i)=>n-i);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:un(t,.5),p95Value:un(t,.95)})}function un(r,e){return r[Math.ceil(e*r.length)-1]}function Co(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}function xs(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var We=V(R(),1),cn=class r{static async createAsync(e,t){let n=!We.PipelineFactory.getAsyncCompilation(e),i=n?We.PipelineFactory.beginAsyncCompilation(e):We.PipelineFactory.getAsyncCompilation(e),o;try{o=new r(e,t)}finally{n&&We.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await o._pipelineInitialization,o}catch(s){throw o.destroy(),s}}device;id;vertexSource;fragmentSource;pipelineFactory;shaderFactory;vertexShader;fragmentShader;pipeline;_pipelineInitialization;_destroyed=!1;drawDefaults;constructor(e,t){if(e.type!=="webgpu"&&e.type!=="webgl")throw new Error("RenderKernel requires WebGL or WebGPU");if(e.type==="webgl"&&!t.fragmentSource)throw new Error("WebGL RenderKernel requires a fragment shader");let{vertexSource:n,fragmentSource:i,pipelineFactory:o,shaderFactory:s,debugShaders:a,...u}=t;this.device=e,this.drawDefaults={parameters:t.parameters??{},topology:t.topology??"triangle-list"},this.id=t.id??"render-kernel",this.vertexSource=n,this.fragmentSource=i,this.pipelineFactory=o??We.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=s??We.ShaderFactory.getDefaultShaderFactory(e),this.vertexShader=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.vertexSource,debugShaders:a}),this.fragmentShader=this.fragmentSource?this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fragmentSource,debugShaders:a}):null;let c={...u,vs:this.vertexShader,fs:this.fragmentShader},f=We.PipelineFactory.getAsyncCompilation(e);if(f){let d=this.pipelineFactory.createRenderPipelineAsync(c);this._pipelineInitialization=d,f.push(d.then(l=>(this.pipeline=l,l)))}else this.pipeline=this.pipelineFactory.createRenderPipeline(c)}draw(e,t){let{bindings:n={},vertexArray:i,...o}=t;return this._setPipeline(e,n,i),e.draw(this.device.type==="webgl"?{...this.drawDefaults,...o,isInstanced:o.isInstanced??o.instanceCount!==void 0}:o)}drawIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:i,indirectBuffer:o,indirectOffset:s=0}=t;this._setPipeline(e,n,i),e.drawIndirect(o,s)}drawIndexedIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:i,indirectBuffer:o,indirectOffset:s=0}=t;this._setPipeline(e,n,i),e.drawIndexedIndirect(o,s)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.vertexShader),this.fragmentShader&&this.shaderFactory.release(this.fragmentShader),this._destroyed=!0)}_setPipeline(e,t,n){e.setPipeline(this.pipeline),e.setBindings(t),e.setVertexArray(n)}};var Lo=V(R(),1);var dn=class{type="compaction";id;props;constructor(e){this.id=e.id??`${e.output}-compaction`,this.props=Object.freeze({...e})}get contract(){let{input:e,flags:t,output:n,count:i}=this.props;return{outputs:({getValue:o})=>{for(let s of[e,t]){let a=o(s);(0,Lo.assert)(a.type==="vector"&&a.format==="uint32")}return(0,Lo.assert)(n!==i),{[n]:W.vector("uint32"),[i]:W.scalar("uint32")}},values:[{value:e,access:"read"},{value:t,access:"read"},{value:n,access:"write",shape:{like:e}},{value:i,access:"write"}]}}};return Bs(pr);})();
413
+ let index = (workgroup.y * dimensions.x + workgroup.x) * ${Lo}u + localIndex;
414
+ if (index >= ${i(0)}) { return; }
415
+ ${d}
416
+ }`,shaderLayout:{bindings:u}})}lower(e){let t=this.vectorNames.map(u=>e.resolveVector(this.program.vectors.find(c=>c.id===u))),n=this.outputIsScalar?e.resolveScalar(this.program.scalars.find(u=>u.id===this.plan.operation.output)):void 0,o=this.outputIsScalar?void 0:e.resolveVector(this.program.vectors.find(u=>u.id===this.plan.operation.output)),i=n?.arena??(this.scalarNames.length?e.resolveScalar(this.program.scalars.find(u=>u.id===this.scalarNames[0])).arena:void 0),a=(o?.data??[n.view]).flatMap((u,c)=>{if(u.length===0)return[];let d=t.map(y=>y.data[c]);if(d.some(y=>!y||y.length!==u.length))throw new Error("Expression chunk mismatch");let f=Math.ceil(u.length/Lo),l=e.graph.device.limits.maxComputeWorkgroupsPerDimension,h=Math.min(f,l),m=Math.ceil(f/h);if(m>l)throw new Error("Expression chunk exceeds dispatch limits");let g=[...d.map(y=>({buffer:y,usage:"storage-read"})),...o?[{buffer:u,usage:"storage-write"}]:[],...i?[{buffer:i.buffer,usage:this.outputIsScalar?"storage-read-write":"storage-read"}]:[]];return[W(j({id:`${this.plan.operation.id}-chunk-${c}`,resources:g,compile:({device:y})=>{let p=new Uint32Array(Math.ceil((this.vectorNames.length+2)/4)*4);p.set([u.length,L(u),...d.map(L)]);let w=y.createBuffer({data:p,usage:bs.Buffer.UNIFORM});return{encode:({computePass:S,getBuffer:v})=>{let T={metadata:w};d.forEach((b,P)=>{T[`input${P}`]=$(b,v)}),o&&(T.outputValues=$(u,v)),i&&(T.gpuValues=v(i.buffer)),this.kernel.dispatch(S,{bindings:T,x:h,y:m,z:1})},destroy:()=>w.destroy()}}}),[h,m,1])]});Me(e.graph,a),e.recordDecision({operationId:this.plan.operation.id,operationType:"expression",lowering:"webgpu-expression",reason:"shape-independent expression shader with execution-time chunk dimensions"})}destroy(){this.kernel.destroy()}};var oe=R(A(),1);var We=R(A(),1),zt=class r{static async createAsync(e,t){let n=!We.PipelineFactory.getAsyncCompilation(e),o=n?We.PipelineFactory.beginAsyncCompilation(e):We.PipelineFactory.getAsyncCompilation(e),i;try{i=new r(e,t)}finally{n&&We.PipelineFactory.endAsyncCompilation(e,o)}try{return n?await Promise.all(o):await i._pipelineInitialization,i}catch(s){throw i.destroy(),s}}device;id;vertexSource;fragmentSource;pipelineFactory;shaderFactory;vertexShader;fragmentShader;pipeline;_pipelineInitialization;_destroyed=!1;drawDefaults;constructor(e,t){if(e.type!=="webgpu"&&e.type!=="webgl")throw new Error("RenderKernel requires WebGL or WebGPU");if(e.type==="webgl"&&!t.fragmentSource)throw new Error("WebGL RenderKernel requires a fragment shader");let{vertexSource:n,fragmentSource:o,pipelineFactory:i,shaderFactory:s,debugShaders:a,...u}=t;this.device=e,this.drawDefaults={parameters:t.parameters??{},topology:t.topology??"triangle-list"},this.id=t.id??"render-kernel",this.vertexSource=n,this.fragmentSource=o,this.pipelineFactory=i??We.PipelineFactory.getDefaultPipelineFactory(e),this.shaderFactory=s??We.ShaderFactory.getDefaultShaderFactory(e),this.vertexShader=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.vertexSource,debugShaders:a}),this.fragmentShader=this.fragmentSource?this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fragmentSource,debugShaders:a}):null;let c={...u,vs:this.vertexShader,fs:this.fragmentShader},d=We.PipelineFactory.getAsyncCompilation(e);if(d){let f=this.pipelineFactory.createRenderPipelineAsync(c);this._pipelineInitialization=f,d.push(f.then(l=>(this.pipeline=l,l)))}else this.pipeline=this.pipelineFactory.createRenderPipeline(c)}draw(e,t){let{bindings:n={},vertexArray:o,...i}=t;return this._setPipeline(e,n,o),e.draw(this.device.type==="webgl"?{...this.drawDefaults,...i,isInstanced:i.isInstanced??i.instanceCount!==void 0}:i)}drawIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:o,indirectBuffer:i,indirectOffset:s=0}=t;this._setPipeline(e,n,o),e.drawIndirect(i,s)}drawIndexedIndirect(e,t){if(this.device.type!=="webgpu")throw new Error("Indirect drawing is only supported in WebGPU");let{bindings:n={},vertexArray:o,indirectBuffer:i,indirectOffset:s=0}=t;this._setPipeline(e,n,o),e.drawIndexedIndirect(i,s)}destroy(){this._destroyed||(this.pipeline&&this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.vertexShader),this.fragmentShader&&this.shaderFactory.release(this.fragmentShader),this._destroyed=!0)}_setPipeline(e,t,n){e.setPipeline(this.pipeline),e.setBindings(t),e.setVertexArray(n)}};var Hu=`
417
+ struct GraphShaderPassVertex {
418
+ @builtin(position) position: vec4<f32>,
419
+ @location(0) textureCoordinates: vec2<f32>
420
+ };
421
+ @vertex fn vertexMain(@builtin(vertex_index) index: u32) -> GraphShaderPassVertex {
422
+ let position = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));
423
+ var result: GraphShaderPassVertex;
424
+ result.position = vec4<f32>(position * 2.0 - 1.0, 0.0, 1.0);
425
+ result.textureCoordinates = vec2<f32>(position.x, 1.0 - position.y);
426
+ return result;
427
+ }`,un=class{device;operation;kernel;vertexArray;samplers=Object.create(null);parameterFormats;parameterByteLength;constructor(e,t,n){this.device=e,this.operation=t,(0,oe.assert)(e.type==="webgpu"),this.parameterFormats=Object.values(t.parameters).map(u=>{let c=n.scalars.find(d=>d.id===u);return(0,oe.assert)(c),c.format}),this.parameterByteLength=Math.ceil(this.parameterFormats.length/4)*16;for(let u of Object.values(t.inputs)){let c=n.textures.find(f=>f.id===u),d=e.getTextureFormatInfo(c.format);(0,oe.assert)(!d.integer&&d.attachment!=="depth"&&d.attachment!=="depth-stencil"&&e.getTextureFormatCapabilities(c.format).filter)}let o=e.getTextureFormatInfo(t.outputDescriptor.format);(0,oe.assert)(!o.integer&&e.getTextureFormatCapabilities(t.outputDescriptor.format).render);let i=[...Object.keys(t.inputs).map((u,c)=>({name:u,location:c,group:0,type:"texture",viewDimension:"2d",sampleType:"float"})),...Object.keys(t.samplers).map((u,c)=>({name:u,location:Object.keys(t.inputs).length+c,group:0,type:"sampler"}))],s=0,a=[...Object.keys(t.inputs).map(u=>`@group(0) @binding(${s++}) var ${u}: texture_2d<f32>;`),...Object.keys(t.samplers).map(u=>`@group(0) @binding(${s++}) var ${u}: sampler;`)];this.parameterFormats.length&&(i.push({name:"parameters",location:s,group:0,type:"uniform"}),a.push(`struct GraphShaderPassParameters {${Object.keys(t.parameters).map((u,c)=>`${u}: ${is(this.parameterFormats[c])}`).join(",")}};
428
+ @group(0) @binding(${s}) var<uniform> parameters: GraphShaderPassParameters;`));try{this.kernel=new zt(e,{id:t.id,vertexSource:Hu,fragmentSource:`${a.join(`
429
+ `)}
430
+ ${t.fragmentSource}
431
+
432
+ @fragment fn fragmentMain(@location(0) textureCoordinates: vec2<f32>) -> @location(0) vec4<f32> {
433
+ return shade(textureCoordinates);
434
+ }`,vertexEntryPoint:"vertexMain",fragmentEntryPoint:"fragmentMain",topology:"triangle-list",shaderLayout:{attributes:[],bindings:i},colorAttachmentFormats:[t.outputDescriptor.format],parameters:{depthWriteEnabled:!1}}),this.vertexArray=e.createVertexArray({shaderLayout:this.kernel.pipeline.shaderLayout,bufferLayout:[]});for(let[u,c]of Object.entries(t.samplers))this.samplers[u]=e.createSampler(c)}catch(u){throw this.destroy(),u}}validateTextures(e){for(let t of[...Object.values(this.operation.inputs),this.operation.output]){let n=e.get(t);(0,oe.assert)(n);let o=Q(n);(0,oe.assert)(o.texture.device===this.device&&o.dimension==="2d"&&o.depth===1&&o.samples===1),t===this.operation.output&&(0,oe.assert)(o.mipLevels===1)}}lower(e){let t=this.operation,n=Object.fromEntries(Object.entries(t.inputs).map(([s,a])=>[s,e.resolveTextureView(a)])),o=e.resolveTextureView(t.output),i=this.parameterFormats.length?e.graph.createTransientBuffer({id:e.graph.getUniqueResourceId(`${t.id}-parameters`),byteLength:this.parameterByteLength,usage:oe.Buffer.UNIFORM|oe.Buffer.COPY_DST}):void 0;if(i){let s=Object.values(t.parameters).map(a=>e.resolveScalar(a).view);e.graph.addCopyPass({id:`${t.id}-parameters`,resources:[...s.map(a=>({buffer:a,usage:"copy-source"})),{buffer:i,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:a,getBuffer:u})=>{s.forEach((c,d)=>a.copyBufferToBuffer({sourceBuffer:u(c),sourceOffset:c.byteOffset,destinationBuffer:u(i),destinationOffset:d*4,size:4}))}})})}e.graph.addRenderPass({id:t.id,resources:[...Object.values(n).map(s=>({texture:s,usage:"sampled"})),...i?[{buffer:i,usage:"uniform"}]:[]],attachments:{colorAttachments:[o]},compile:()=>({getRenderPassProps:()=>({clearColor:[0,0,0,0],clearDepth:!1}),encode:({renderPass:s,getTextureView:a,getBuffer:u})=>this.draw(s,Object.fromEntries(Object.entries(n).map(([c,d])=>[c,a(d)])),i?u(i):void 0)})})}prepare(e,t){this.validateTextures(e);let n=Object.fromEntries(Object.entries(this.operation.inputs).map(([f,l])=>[f,e.get(l)])),o=e.get(this.operation.output),i=Q(o),s=new Uint8Array(this.parameterByteLength),a=new DataView(s.buffer),u=Object.values(this.operation.parameters).map((f,l)=>{let h=t.get(f);if((0,oe.assert)(h!==void 0),typeof h=="number")switch(this.parameterFormats[l]){case"float32":a.setFloat32(l*4,h,!0);break;case"sint32":a.setInt32(l*4,h,!0);break;case"uint32":a.setUint32(l*4,h,!0);break}else(0,oe.assert)(h.length===1&&h.data.length===1);return h}),c=s.byteLength?this.device.createBuffer({data:s,usage:oe.Buffer.UNIFORM|oe.Buffer.COPY_DST}):void 0,d;try{d=this.device.createFramebuffer({width:i.width,height:i.height,colorAttachments:[o]})}catch(f){throw c?.destroy(),f}return{encode:f=>{this.validateTextures(e),c&&u.forEach((h,m)=>{if(!(h instanceof z))return;let g=h.data[0],y=g.buffer instanceof oe.Buffer?g.buffer:g.buffer.buffer;f.copyBufferToBuffer({sourceBuffer:y,sourceOffset:g.byteOffset,destinationBuffer:c,destinationOffset:m*4,size:4})});let l=f.beginRenderPass({framebuffer:d,clearColor:[0,0,0,0],clearDepth:!1});try{this.draw(l,n,c)}finally{l.end()}},destroy:()=>{d.destroy(),c?.destroy()}}}destroy(){for(let e of Object.values(this.samplers))e.destroy();this.vertexArray?.destroy(),this.kernel?.destroy()}draw(e,t,n){let o={...t,...this.samplers};n&&(o.parameters=n),this.kernel.draw(e,{vertexArray:this.vertexArray,vertexCount:3,bindings:o})}};var be=class{type="cpu";id;inputs;outputs;execute;constructor(e){this.id=e.id,this.inputs=Object.freeze({...e.inputs}),this.outputs=Object.freeze(Object.fromEntries(Object.entries(e.outputs).map(([t,n])=>[t,Object.freeze({...n,...n.chunkLengths?{chunkLengths:Object.freeze([...n.chunkLengths])}:{}})]))),this.execute=e.execute}get contract(){return{outputs:this.outputs,values:[...Object.values(this.inputs).map(e=>({value:e,access:"read"})),...Object.keys(this.outputs).map(e=>({value:e,access:"write"}))]}}};var ee=R(A(),1);var pr=class{device;program;compileStage;stages=[];constructor(e,t,n){this.device=e,this.program=t,this.compileStage=n,(0,ee.assert)(!t.textures.length&&!t.vectors.some(s=>s.role==="state"));let o=[...t.scalars,...t.vectors],i=(s,a)=>{let u=o.find(d=>d.id===a);(0,ee.assert)(u);let c=t.vectors.find(d=>d.id===a);c?s.addInput(a,N.vector(c.format,{length:c.length,chunkLengths:c.chunkLengths})):s.addInput(a,N.scalar(t.scalars.find(d=>d.id===a).format))};try{for(let s of t.operations){if(s instanceof be){this.stages.push(s);continue}(0,ee.assert)("contract"in s&&s.contract);let a=s.contract.values.filter(d=>d.access!=="write").map(d=>typeof d.value=="string"?d.value:d.value.id),u=s.contract.values.filter(d=>d.access!=="read").map(d=>typeof d.value=="string"?d.value:d.value.id),c=new Ce;for(let d of new Set(a))i(c,d);for(let d of new Set(u)){let f=t.vectors.find(l=>l.id===d);f&&c.addDeclaration(d,N.vector(f.format,{length:f.length,chunkLengths:f.chunkLengths}),"value")}c.add(s),this.stages.push({graph:n(c,u),inputs:a})}}catch(s){throw this.destroy(),s}}async run(e,t={}){for(let[u,c]of Object.entries(t))(0,ee.assert)(this.program.outputs.includes(u)&&(c==="cpu"||c==="gpu"));let n=new Map;for(let u of[...this.program.vectors,...this.program.scalars].filter(c=>c.role==="input")){let c=e[u.id];if((0,ee.assert)(c!==void 0),!(c instanceof Te)){let d=new Ce,f=this.program.vectors.find(l=>l.id===u.id);f?d.addInput(u.id,N.vector(f.format,{length:f.length,chunkLengths:f.chunkLengths})):d.addInput(u.id,N.scalar(this.program.scalars.find(l=>l.id===u.id).format)),new Vt(d,{outputs:[]}).prepare(this.device,{[u.id]:c}).finish()}if(c instanceof Te){(0,ee.assert)(c.data.every(f=>!f.nullBitmap&&!f.valueOffsets)),(0,ee.assert)(c.format===u.format);let d=this.program.vectors.find(f=>f.id===u.id);(0,ee.assert)(d&&(d.length===void 0||d.length===c.length)),(0,ee.assert)(!d.chunkLengths||d.chunkLengths.length===c.data.length&&d.chunkLengths.every((f,l)=>f===c.data[l].length)),n.set(u.id,c)}}let o={...e},i=new Set,s=async u=>{let c=n.get(u);if(!c){let d=o[u];(0,ee.assert)(d instanceof z);let f=await qu(d);c=xs(f.format,f.chunks.map(l=>l.values)),n.set(u,c)}return Yu(c)},a=async u=>{let c=o[u];if(c instanceof z)return c;let d=await s(u),f=new Ce;f.add(new Ve({output:u,format:d.format,data:d.chunks.map(h=>h.values)}));let l=this.compileStage(f);try{let h=(await l.run({}))[u];return i.add(h),o[u]=h,h}finally{l.destroy()}};try{for(let c of this.stages){let d;if(c instanceof be){let f=Object.create(null);for(let[h,m]of Object.entries(c.inputs)){let g=o[m],y=typeof g=="number"?g:await s(m);f[h]=typeof y!="number"&&this.program.scalars.some(p=>p.id===m)?y.pack()[0]:y}let l=await c.execute({inputs:f});(0,ee.assert)(Object.keys(l).length===Object.keys(c.outputs).length);for(let h of Object.keys(c.outputs)){let m=this.program.vectors.find(S=>S.id===h),g=l[h];(0,ee.assert)(g);let y="chunks"in g?g.chunks.map(S=>S.values):[g],p=new Ve({output:h,format:m.format,data:y}),w=p.chunkLengths.reduce((S,v)=>S+v,0);(0,ee.assert)(m.length===void 0||m.length===w),(0,ee.assert)(!m.chunkLengths||m.chunkLengths.length===y.length&&m.chunkLengths.every((S,v)=>S===p.chunkLengths[v])),n.set(h,xs(m.format,y)),delete o[h]}continue}else{let f=Object.create(null);for(let l of c.inputs){let h=o[l];f[l]=this.program.scalars.some(m=>m.id===l)?typeof h=="number"?h:(await s(l)).pack()[0]:await a(l)}d=await c.graph.run({inputs:f})}for(let[f,l]of Object.entries(d))n.delete(f),o[f]=l,i.add(l)}let u=Object.create(null);for(let c of this.program.outputs)t[c]==="cpu"?(await s(c),u[c]=n.get(c)):u[c]=await a(c);for(let c of Object.values(u))c instanceof z&&i.delete(c);return u}finally{for(let u of i)u.destroy()}}destroy(){for(let e of this.stages)e instanceof be||e.graph.destroy()}};async function qu(r){(0,ee.assert)(r.format);let e=I(r.format),t=e.signedDataType==="float32"?Float32Array:e.signedDataType==="uint32"?Uint32Array:Int32Array,n=[];for(let o of r.data){let i=new t(o.length*e.byteLength/4);if(o.length){let s=await o.buffer.readAsync(o.byteOffset,(o.length-1)*o.byteStride+e.byteLength),a=new Uint8Array(i.buffer);for(let u=0;u<o.length;u++)a.set(s.subarray(u*o.byteStride,u*o.byteStride+e.byteLength),u*e.byteLength)}n.push({values:i,length:o.length})}return{format:r.format,length:r.length,chunks:n,pack(){let o=new t(n.reduce((s,a)=>s+a.values.length,0)),i=0;for(let s of n)o.set(s.values,i),i+=s.values.length;return o}}}function xs(r,e){let t=I(r).byteLength;return new Te({format:r,data:e.map(n=>new nr({buffer:n,format:r,length:n.byteLength/t}))})}function Yu(r){let e=r.format;(0,ee.assert)(/^(float32|sint32|uint32)(x[234])?$/.test(e));let t=I(e),n=t.signedDataType==="float32"?Float32Array:t.signedDataType==="uint32"?Uint32Array:Int32Array,o=r.data.map(i=>{let s=new n(i.length*t.components),a=new Uint8Array(s.buffer);for(let u=0;u<i.length;u++)a.set(new Uint8Array(i.buffer,i.byteOffset+u*i.byteStride,t.byteLength),u*t.byteLength);return{values:s,length:i.length}});return{format:e,length:r.length,chunks:o,pack(){let i=new n(r.length*t.components),s=0;for(let a of o)i.set(a.values,s),s+=a.values.length;return i}}}var jt=class r{device;program;stageLowerings;compiler;kernels=new Map;shaderPasses=new Map;destroyed=!1;runningCPU=!1;cpuExecution;outputLocations;constructor(e,t,n={},o){if(this.device=e,e.type!=="webgpu")throw new Error("GPUGraph execution requires WebGPU");if(this.program=new Vt(t,n),this.outputLocations=n.outputLocations??{},this.stageLowerings=o??n.lowerings??[],this.compiler=new wt(e,[...o??n.lowerings??[],{type:"shader-pass",lower:(i,s)=>this.shaderPasses.get(i).lower(s)},{type:"expression",lower:(i,s)=>this.kernels.get(i).lower(s)}]),this.program.operations.some(i=>i instanceof be)||Object.values(this.outputLocations).includes("cpu")){this.cpuExecution=new pr(e,this.program,(i,s)=>new r(e,i,{outputs:s},o??n.lowerings));return}try{for(let i of this.program.expressions)this.kernels.set(i.operation,new an(e,this.program,i));for(let i of this.program.operations)i instanceof at&&this.shaderPasses.set(i,new un(e,i,this.program))}catch(i){throw this.destroy(),i}}async run(e,t={}){(0,vt.assert)(!this.destroyed&&!this.runningCPU);let n="inputs"in e?e.inputs:e,o=this.program.operations.some(a=>a instanceof be)||Object.values(this.outputLocations).includes("cpu")||Object.values(n??{}).some(a=>a instanceof Te);if(!this.cpuExecution&&o&&(this.cpuExecution=new pr(this.device,this.program,(a,u)=>new r(this.device,a,{outputs:u},this.stageLowerings))),o&&this.cpuExecution){let a=this.program.resolveBindings(e,t);(0,vt.assert)(!a.options.outputTargets||Object.keys(a.options.outputTargets).length===0),this.runningCPU=!0;try{return await this.cpuExecution.run(a.bindings,this.outputLocations)}finally{this.runningCPU=!1}}let i=this.prepare(e,t),s;try{return s=this.device.createCommandEncoder(),i.encode(s),this.device.submit(s.finish()),i.outputs}catch(a){throw i.discard(),a}finally{i.destroy(),s?.destroy()}}prepare(e,t={}){if((0,vt.assert)(!this.destroyed),this.program.operations.some(a=>a instanceof be)||Object.values(this.outputLocations).includes("cpu"))throw new Error("CPU operations require asynchronous run(), not prepare()");let n=this.program.resolveBindings(e,t),o=n.bindings;t=n.options;let i=this.program.prepare(this.device,o,t,!0),s;try{for(let l of this.shaderPasses.values())l.validateTextures(i.textures.values);let a=new Ce;for(let l of this.program.scalars)a.scalar(l.id,l.format);let u=Object.create(null),c=Object.create(null);for(let[l,h]of i.values)typeof h=="number"?c[l]=h:this.program.vectors.some(m=>m.id===l)&&(u[l]=h);for(let[l,h]of Object.entries(o))typeof h=="number"&&(c[l]=h);for(let l of this.program.vectors){let h=u[l.id],m=i.transientVectors.get(l.id);if(m){a.addDeclaration(l.id,{type:"vector",format:l.format,length:m.length,chunkLengths:m.chunkLengths},"value");continue}if(!h&&l.length===void 0)throw new Error(`Missing length or execution binding for ${l.id}`);a.vector(l.id,l.format,h?.length??l.length,{external:!!h,chunkLengths:h?.data.map(g=>g.length)??l.chunkLengths})}let d=Object.create(null);for(let l of this.program.textures){let h=i.textures.values.get(l.id),m=Q(h);a.texture(l.id,{format:m.format,dimension:m.dimension,width:m.width,height:m.height,depth:m.depth,mipLevels:m.mipLevels,samples:m.samples,usage:m.texture.props.usage,external:!0}),d[l.id]=h}a.add(this.program.operations);let f=this.compiler.compile(a,{vectors:u,scalars:c,textures:d});for(let l of this.program.scalars){let h=i.values.get(l.id);if(!(h instanceof z))continue;let m=f.scalars.get(l.id).view,g=f.graph.importGPUVector(`${l.id}-result`,h).data[0];f.graph.addCopyPass({id:`${l.id}-result-copy`,resources:[{buffer:m,usage:"copy-source"},{buffer:g,usage:"copy-destination"}],compile:()=>({encode:({commandEncoder:y,getBuffer:p})=>y.copyBufferToBuffer({sourceBuffer:p(m),sourceOffset:m.byteOffset,destinationBuffer:p(g),destinationOffset:g.byteOffset,size:4})})})}return s=f.graph.compile(),new gr(this.device,i,s,()=>{(0,vt.assert)(!this.destroyed)})}catch(a){throw s?.destroy(),i.destroy(),a}}destroy(){(0,vt.assert)(!this.runningCPU),this.cpuExecution?.destroy();for(let e of this.shaderPasses.values())e.destroy();this.shaderPasses.clear();for(let e of this.kernels.values())e.destroy();this.kernels.clear(),this.destroyed=!0}},gr=class{device;invocation;executable;checkProgram;outputs;encoded=!1;destroyed=!1;constructor(e,t,n,o){this.device=e,this.invocation=t,this.executable=n,this.checkProgram=o,this.outputs=t.getOutputs()}encode(e){(0,vt.assert)(!this.destroyed&&!this.encoded&&e.device===this.device),this.checkProgram(),this.encoded=!0,this.executable.encode(e,{parameters:void 0})}destroy(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.finish())}discard(){this.destroyed||(this.destroyed=!0,this.executable.destroy(),this.invocation.destroy())}};var Ce=class r{id;programOperations=[];programScalars=new Map;programVectors=new Map;programTextures=new Map;constructor(e={}){this.id=e.id??"gpu-program"}add(e){return this.assertOperationLike(e),this.addOperationLike(e),this}addInput(e,t){return this.addDeclaration(e,t,"input")}addState(e,t){if(t.type!=="vector")throw new Error("Graph state requires vector storage");return this.addDeclaration(e,t,"state")}addDeclaration(e,t,n){if(this.assertValueId(e),t.type==="texture"){let i=new ae({id:e,...t,usage:0,role:n,descriptor:t,external:n==="input",..."width"in(t.extent??{})?t.extent:{}});return this.programTextures.set(e,i),i}if(t.type==="scalar"){let i=new Ie(e,t.format,n);return this.programScalars.set(e,i),i}let o=new K({id:e,...t,role:n,external:n==="input"||n==="state"});return this.programVectors.set(e,o),o}scalar(e,t){this.assertValueId(e);let n=new Ie(e,t);return this.programScalars.set(e,n),n}vector(e,t,n,o={}){this.assertValueId(e);let i=typeof n=="number"?{length:n,...o}:n??o,s=new K({id:e,format:t,...i});return this.programVectors.set(e,s),s}texture(e,t){this.assertValueId(e);let n=new ae({...t,id:e});return this.programTextures.set(e,n),n}textureView(e,t={}){if(this.programTextures.get(e.id)!==e)throw new Error(`Undeclared program texture "${e.id}"`);return new Ue(e,t)}compile(e,t={}){return new jt(e,this,t)}constrainResult(e,t){if(e.length!==void 0&&t.length!==void 0&&e.length!==t.length)throw new Error(`Incompatible result length ${e.id}`);if(e.chunkLengths&&t.chunkLengths&&(e.chunkLengths.length!==t.chunkLengths.length||e.chunkLengths.some((o,i)=>o!==t.chunkLengths[i])))throw new Error(`Incompatible result chunks ${e.id}`);let n=new K({...e,length:e.length??t.length,chunkLengths:e.chunkLengths??t.chunkLengths});return this.programVectors.set(e.id,n),n}clone(){let e=new r({id:this.id});for(let[t,n]of this.programScalars)e.programScalars.set(t,n);for(let[t,n]of this.programVectors)e.programVectors.set(t,n);for(let[t,n]of this.programTextures)e.programTextures.set(t,n);return e.programOperations.push(...this.programOperations),e}get textures(){return Object.freeze([...this.programTextures.values()])}get scalars(){return Object.freeze([...this.programScalars.values()])}get vectors(){return Object.freeze([...this.programVectors.values()])}get operations(){return Object.freeze([...this.programOperations])}get operationTree(){return Object.freeze(this.programOperations.map(vo))}assertValueId(e){if(this.programScalars.has(e)||this.programVectors.has(e)||this.programTextures.has(e))throw new Error(`${this.id} value "${e}" already exists`)}addOperationLike(e){if(Array.isArray(e)){for(let t of e)this.addOperationLike(t);return}this.programOperations.push(e)}assertOperationLike(e){if(Array.isArray(e)){for(let t of e)this.assertOperationLike(t);return}if(!e||typeof e!="object")throw new Error(`${this.id} accepts GPU operations only`)}};function Bo(r,e={}){return new H({id:e.id,operations:r})}function Oo(r){let e=r.lowering.decisions.map(t=>`${t.operationId}: ${t.lowering} \u2014 ${t.reason}`);return Object.freeze({programId:r.program.id,semanticOperationCount:ws(r.program.operationTree),loweredNodeCount:r.lowering.nodes.length,loweringDecisionCount:r.lowering.decisions.length,scalarCount:r.program.scalars.length,vectorCount:r.program.vectors.length,externalVectorCount:r.program.vectors.filter(t=>t.external).length,cpuReadbackCount:0,backend:"webgpu",decisions:Object.freeze(e)})}function ws(r){return r.reduce((e,t)=>e+1+ws(t.children??[]),0)}var dn=class{adapter;minimumSampleCount;explorationEnabled;calibrations=new Map;constructor(e){if(!Number.isSafeInteger(e.minimumSampleCount??1)||(e.minimumSampleCount??1)<=0)throw new Error("GPUCommandGraph autotuner minimumSampleCount must be a positive safe integer");if(this.adapter=Xu(e.adapter),this.minimumSampleCount=e.minimumSampleCount??1,this.explorationEnabled=e.explorationEnabled??!0,e.profile?.adapter.key===this.adapter.key&&e.profile.version===1)for(let t of e.profile.calibrations)this.importCalibration(t)}selectKernel(e){cn(e.operation,"operation"),Ss(e.workloadSize);let t=e.candidates.filter(a=>a.supported!==!1);if(t.length===0)throw new Error(`GPUCommandGraph autotuner operation "${e.operation}" has no supported variants`);for(let a of t)cn(a.id,"variant");let n=vs(e.workloadSize),o=t.map(a=>{let u=this.findNearestCalibration(e.operation,a.id,n);return{candidate:a,calibration:u,sampleCount:u?.workloadBucket===n?u.sampleCount:0,estimatedDurationMilliseconds:u?Ku(u,e.workloadSize):void 0}});if(this.explorationEnabled){let a=o.find(u=>u.sampleCount<this.minimumSampleCount);if(a)return Object.freeze({operation:e.operation,variant:a.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:"exploration",sampleCount:a.sampleCount,...a.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:a.estimatedDurationMilliseconds}})}let i=o.filter(a=>a.estimatedDurationMilliseconds!==void 0).sort((a,u)=>(a.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY)-(u.estimatedDurationMilliseconds??Number.POSITIVE_INFINITY))[0],s=i??o[0];return Object.freeze({operation:e.operation,variant:s.candidate.id,workloadSize:e.workloadSize,workloadBucket:n,reason:i?"calibrated":"fallback",sampleCount:s.calibration?.sampleCount??0,...s.estimatedDurationMilliseconds===void 0?{}:{estimatedDurationMilliseconds:s.estimatedDurationMilliseconds}})}observeKernel(e){if(cn(e.operation,"operation"),cn(e.variant,"variant"),Ss(e.workloadSize),!Number.isFinite(e.durationMilliseconds)||e.durationMilliseconds<0)throw new Error("GPUCommandGraph autotuner durationMilliseconds must be nonnegative");let t=vs(e.workloadSize),n=Go(e.operation,e.variant,t),o=this.calibrations.get(n)??{operation:e.operation,variant:e.variant,workloadBucket:t,sampleCount:0,meanWorkloadSize:0,meanDurationMilliseconds:0,durationSquaredDifferenceSum:0};o.sampleCount++,o.meanWorkloadSize+=(e.workloadSize-o.meanWorkloadSize)/o.sampleCount;let i=e.durationMilliseconds-o.meanDurationMilliseconds;return o.meanDurationMilliseconds+=i/o.sampleCount,o.durationSquaredDifferenceSum+=i*(e.durationMilliseconds-o.meanDurationMilliseconds),this.calibrations.set(n,o),Ts(o)}observeTimingReport(e,t){let n=new Map(t.nodes.map(i=>[i.id,i])),o=0;for(let i of e.nodes){let s=n.get(i.id);i.gpuTimeMilliseconds===void 0||!s?.operation||!s.variant||(this.observeKernel({operation:s.operation,variant:s.variant,workloadSize:Math.max(s.maximumInvocationCount,1),durationMilliseconds:i.gpuTimeMilliseconds}),o++)}return o}exportProfile(){let e=[...this.calibrations.values()].sort((t,n)=>t.operation.localeCompare(n.operation)||t.variant.localeCompare(n.variant)||t.workloadBucket-n.workloadBucket).map(Ts);return Object.freeze({version:1,adapter:this.adapter,calibrations:Object.freeze(e)})}reset(){this.calibrations.clear()}importCalibration(e){!e.operation||!e.variant||!Number.isSafeInteger(e.workloadBucket)||!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0||!Number.isFinite(e.meanWorkloadSize)||e.meanWorkloadSize<=0||!Number.isFinite(e.meanDurationMilliseconds)||e.meanDurationMilliseconds<0||this.calibrations.set(Go(e.operation,e.variant,e.workloadBucket),{operation:e.operation,variant:e.variant,workloadBucket:e.workloadBucket,sampleCount:e.sampleCount,meanWorkloadSize:e.meanWorkloadSize,meanDurationMilliseconds:e.meanDurationMilliseconds,durationSquaredDifferenceSum:e.sampleCount>1?e.durationStandardDeviationMilliseconds**2*(e.sampleCount-1):0})}findNearestCalibration(e,t,n){let o=this.calibrations.get(Go(e,t,n));if(o)return o;let i;for(let s of this.calibrations.values())s.operation!==e||s.variant!==t||(!i||Math.abs(s.workloadBucket-n)<Math.abs(i.workloadBucket-n))&&(i=s);return i}};function Es(r){let e=[...r.features].sort(),t={type:r.info.type,vendor:r.info.vendor,renderer:r.info.renderer,version:r.info.version,gpu:r.info.gpu,gpuType:r.info.gpuType,...r.info.gpuArchitecture?{gpuArchitecture:r.info.gpuArchitecture}:{},...r.info.gpuBackend?{gpuBackend:r.info.gpuBackend}:{},...r.info.featureLevel?{featureLevel:r.info.featureLevel}:{},features:Object.freeze(e),...r.info.subgroupMinSize===void 0?{}:{subgroupMinSize:r.info.subgroupMinSize},...r.info.subgroupMaxSize===void 0?{}:{subgroupMaxSize:r.info.subgroupMaxSize},maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension};return Object.freeze({key:JSON.stringify(t),...t})}function Xu(r){return Object.freeze({...r,features:Object.freeze([...r.features])})}function Ts(r){return Object.freeze({operation:r.operation,variant:r.variant,workloadBucket:r.workloadBucket,sampleCount:r.sampleCount,meanWorkloadSize:r.meanWorkloadSize,meanDurationMilliseconds:r.meanDurationMilliseconds,durationStandardDeviationMilliseconds:r.sampleCount>1?Math.sqrt(r.durationSquaredDifferenceSum/(r.sampleCount-1)):0})}function Ku(r,e){return r.meanDurationMilliseconds*(e/Math.max(r.meanWorkloadSize,1))}function vs(r){return Math.floor(Math.log2(Math.max(r,1)))}function Go(r,e,t){return`${r}\0${e}\0${t}`}function cn(r,e){if(!r)throw new Error(`GPUCommandGraph autotuner ${e} is required`)}function Ss(r){if(!Number.isSafeInteger(r)||r<=0)throw new Error("GPUCommandGraph autotuner workloadSize must be a positive safe integer")}var Qu={interactive:4,normal:8,background:16},fn=class{targetStepMilliseconds;latencyPriority;minimumScale;maximumScale;responsiveness;maximumAdjustmentFactor;initialBudget;currentBudget;currentScale=1;currentSampleCount=0;constructor(e){Ps(e.initialBudget);let t=e.latencyPriority??"normal",n=e.targetStepMilliseconds??Qu[t];br(n,"targetStepMilliseconds");let o=e.minimumScale??.125,i=e.maximumScale??4,s=e.responsiveness??.25,a=e.maximumAdjustmentFactor??2;if(br(o,"minimumScale"),br(i,"maximumScale"),br(a,"maximumAdjustmentFactor"),o>1||i<1)throw new Error("GPUCommandGraph budget scale range must contain the initial scale 1");if(!Number.isFinite(s)||s<=0||s>1)throw new Error("GPUCommandGraph budget responsiveness must be in the interval (0, 1]");if(a<1)throw new Error("GPUCommandGraph budget maximumAdjustmentFactor must be at least 1");this.initialBudget=Ls(e.initialBudget),this.currentBudget=this.initialBudget,this.latencyPriority=t,this.targetStepMilliseconds=n,this.minimumScale=o,this.maximumScale=i,this.responsiveness=s,this.maximumAdjustmentFactor=a}get budget(){return this.currentBudget}get sampleCount(){return this.currentSampleCount}reset(){this.currentBudget=this.initialBudget,this.currentScale=1,this.currentSampleCount=0}observeStep(e,t,n=this.currentBudget){br(t,"durationMilliseconds"),Ps(n);let o=Zu(e,n);if(o>0){let i=this.targetStepMilliseconds*Math.min(o,1)/t,a=1+(Cs(i,1/this.maximumAdjustmentFactor,this.maximumAdjustmentFactor)-1)*this.responsiveness;this.currentScale=Cs(this.currentScale*a,this.minimumScale,this.maximumScale),this.currentBudget=Ju(this.initialBudget,this.currentScale)}return this.currentSampleCount++,Object.freeze({sampleCount:this.currentSampleCount,durationMilliseconds:t,targetStepMilliseconds:this.targetStepMilliseconds,latencyPriority:this.latencyPriority,saturation:o,scale:this.currentScale,budget:this.currentBudget})}};function Zu(r,e){let t=[r.maximumInvocationCount/e.maximumInvocationCount];return e.maximumNodeCount!==void 0&&t.push(r.nodeCount/e.maximumNodeCount),e.maximumCommandCount!==void 0&&t.push(r.commandCount/e.maximumCommandCount),e.maximumReadByteLength!==void 0&&t.push(r.readByteLength/e.maximumReadByteLength),e.maximumWriteByteLength!==void 0&&t.push(r.writeByteLength/e.maximumWriteByteLength),Math.max(...t)}function Ju(r,e){return Ls({maximumInvocationCount:yr(r.maximumInvocationCount,e),...r.maximumNodeCount===void 0?{}:{maximumNodeCount:yr(r.maximumNodeCount,e)},...r.maximumCommandCount===void 0?{}:{maximumCommandCount:yr(r.maximumCommandCount,e)},...r.maximumReadByteLength===void 0?{}:{maximumReadByteLength:yr(r.maximumReadByteLength,e)},...r.maximumWriteByteLength===void 0?{}:{maximumWriteByteLength:yr(r.maximumWriteByteLength,e)}})}function yr(r,e){return Math.max(1,Math.min(Number.MAX_SAFE_INTEGER,Math.round(r*e)))}function Ls(r){return Object.freeze({...r})}function br(r,e){if(!Number.isFinite(r)||r<=0)throw new Error(`GPUCommandGraph budget ${e} must be positive`)}function Ps(r){for(let[e,t]of[["maximumInvocationCount",r.maximumInvocationCount],["maximumNodeCount",r.maximumNodeCount],["maximumCommandCount",r.maximumCommandCount],["maximumReadByteLength",r.maximumReadByteLength],["maximumWriteByteLength",r.maximumWriteByteLength]])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))throw new Error(`GPUCommandGraph budget ${e} must be a positive safe integer`)}function Cs(r,e,t){return Math.max(e,Math.min(t,r))}var hn=class{maxSamples;getNodeGroup;graphs=new Map;encodingGraphs=new WeakMap;constructor(e={}){let t=e.maxSamples??120;if(!Number.isSafeInteger(t)||t<=0)throw new Error("GPUCommandGraphInspector maxSamples must be a positive safe integer");this.maxSamples=t,this.getNodeGroup=e.getNodeGroup}registerGraph(e){this.graphs.set(e.id,{id:e.id,stats:ec(e.stats),capabilities:Object.freeze({...e.capabilities}),...e.preflight?{preflight:tc(e.preflight)}:{},encodingCount:0,timingReadFailureCount:0,cpuSamples:[],gpuSamples:[],counters:new Map,nodes:new Map});let t=this.getGraph(e.id);for(let n of e.preflight?.nodes??[])this.getNode(t,n)}observeGraph(e){this.registerGraph(e);let t=this.getGraph(e.id),n=new WeakMap,o=!0,i=()=>o&&this.graphs.get(e.id)===t;return Object.freeze({graph:e,encode:(s,a)=>{let u=e.encode(s,a);return i()&&this.recordGraphEncoding(t,u),u},recordGPUTimings:async s=>{let a=n.get(s);if(a)return await a;if(i()&&this.encodingGraphs.get(s)===t){let u=this.recordGraphGPUTimings(e.id,t,s);return n.set(s,u),await u}},recordCounters:s=>{i()&&this.recordGraphCounters(t,s)},detach:()=>{o&&(o=!1,this.graphs.get(e.id)===t&&this.graphs.delete(e.id))}})}clear(){this.graphs.clear()}recordEncoding(e,t){let n=this.getGraph(e);this.recordGraphEncoding(n,t)}async readResource(e,t,n){let o=this.getGraph(e);if(!o.encoding?.readResource)throw new Error("No live resource readback is available.");let i=await o.encoding.readResource(t,n);if(this.graphs.get(e)!==o)throw new Error("Graph registration changed during readback.");return i}recordCounters(e,t){this.recordGraphCounters(this.getGraph(e),t)}recordGraphEncoding(e,t){e.encoding=t,this.encodingGraphs.set(t,e);let{stats:n}=t;e.encodingCount++,this.addSample(e.cpuSamples,n.cpuEncodeTimeMilliseconds);for(let o of n.nodes){let i=this.getNode(e,o);this.addSample(i.cpuSamples,o.cpuEncodeTimeMilliseconds)}}recordGraphCounters(e,t){let n=Object.entries(t);for(let[o,i]of n)if(!o||!Number.isFinite(i)||i<0)throw new Error("GPUCommandGraphInspector counters require an ID and a finite, non-negative value");for(let[o,i]of n){let s=e.counters.get(o);s||(s=[],e.counters.set(o,s)),this.addSample(s,i)}}async recordGPUTimings(e,t){let o=this.encodingGraphs.get(t)??this.getGraph(e);return await this.recordGraphGPUTimings(e,o,t)}async recordGraphGPUTimings(e,t,n){if(this.graphs.get(e)!==t)return;let o;try{o=await n.readTimings()}catch{this.graphs.get(e)===t&&t.timingReadFailureCount++;return}if(this.graphs.get(e)===t){o.gpuTimeMilliseconds!==void 0&&this.addSample(t.gpuSamples,o.gpuTimeMilliseconds);for(let i of o.nodes)if(i.gpuTimeMilliseconds!==void 0){let s=this.getNode(t,i);this.addSample(s.gpuSamples,i.gpuTimeMilliseconds)}return o}}getSnapshot(){let e=Array.from(this.graphs.values(),t=>this.getGraphSnapshot(t));return Object.freeze({graphs:Object.freeze(e)})}getGraph(e){let t=this.graphs.get(e);if(!t)throw new Error(`GPUCommandGraphInspector graph "${e}" is not registered`);return t}getNode(e,t){let n=e.nodes.get(t.id);if(n)return t.description!==void 0&&(n.description=t.description),t.resources!==void 0&&(n.resources=Do(t.resources)),n;let o=Do(t.resources),i=this.getNodeGroup?.({graphId:e.id,id:t.id,type:t.type,description:t.description,resources:o}),s={id:t.id,resources:o,...t.description===void 0?{}:{description:t.description},type:t.type,...i===void 0?{}:{group:i},cpuSamples:[],gpuSamples:[]};return e.nodes.set(s.id,s),s}addSample(e,t){e.push(t),e.length>this.maxSamples&&e.splice(0,e.length-this.maxSamples)}getGraphSnapshot(e){let t=[],n=new Set;for(let s of e.stats.nodeOrder){let a=e.nodes.get(s);a&&(t.push(a),n.add(s))}for(let s of e.nodes.values())n.has(s.id)||t.push(s);let o=t.map(s=>Object.freeze({id:s.id,resources:s.resources,...s.description===void 0?{}:{description:s.description},type:s.type,...s.group===void 0?{}:{group:s.group},cpu:ln(s.cpuSamples),gpu:ln(s.gpuSamples)})),i=Array.from(e.counters,([s,a])=>rc(s,a));return Object.freeze({id:e.id,stats:e.stats,capabilities:e.capabilities,...e.preflight?{preflight:e.preflight}:{},encodingCount:e.encodingCount,timingReadFailureCount:e.timingReadFailureCount,totals:Object.freeze({cpu:ln(e.cpuSamples),gpu:ln(e.gpuSamples)}),counters:Object.freeze(i),nodes:Object.freeze(o)})}};function ec(r){return Object.freeze({...r,nodeOrder:Object.freeze([...r.nodeOrder])})}function tc(r){return Object.freeze({...r,nodes:Object.freeze(r.nodes.map(e=>Object.freeze({...e,resources:Do(e.resources)})))})}function ln(r){if(r.length===0)return Object.freeze({sampleCount:0});let e=[...r].sort((t,n)=>t-n);return Object.freeze({sampleCount:r.length,latestMilliseconds:r[r.length-1],p50Milliseconds:mn(e,.5),p95Milliseconds:mn(e,.95)})}function rc(r,e){let t=[...e].sort((n,o)=>n-o);return Object.freeze({id:r,sampleCount:e.length,latestValue:e[e.length-1],p50Value:mn(t,.5),p95Value:mn(t,.95)})}function mn(r,e){return r[Math.ceil(e*r.length)-1]}function Do(r){return r&&Object.freeze(r.map(e=>Object.freeze({...e})))}function Bs(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var Io=R(A(),1);var pn=class{type="compaction";id;props;constructor(e){this.id=e.id??`${e.output}-compaction`,this.props=Object.freeze({...e})}get contract(){let{input:e,flags:t,output:n,count:o}=this.props;return{outputs:({getValue:i})=>{for(let s of[e,t]){let a=i(s);(0,Io.assert)(a.type==="vector"&&a.format==="uint32")}return(0,Io.assert)(n!==o),{[n]:N.vector("uint32"),[o]:N.scalar("uint32")}},values:[{value:e,access:"read"},{value:t,access:"read"},{value:n,access:"write",shape:{like:e}},{value:o,access:"write"}]}}};return _s(xr);})();
417
435
  return __exports__;
418
436
  });